java object not compiled - java

I have following java code segment,
class Box{
int length;
int width;
int height;
Box(int length, int width, int height){
this.length=length;
this.width=width;
this.height=height;
}
Box(){
this.length=1;
this.width=1;
this.height=1;
}
}
class Demo{
public static void main(String args[]){
Box b1=new Box(); //calling default
System.out.println("Length : "+b1.length);
System.out.println("Width : "+b1.width);
System.out.println("Height : "+b1.height);
b1.Box(12,5,3);
System.out.println();
}
}
but when I compile the java file following code highlight and not the compile
b1.Box(12,5,3);
what is the problem and how can fix this?

Box(12,5,3) is a parameterized constructor and not a method of Box class, hence there no need to call it using a reference. Just call it directly without using the object.
Therefore, instead of declaring b1 with the default constructor you can use the parameterized one as follows:
Box b1 = new Box(12, 5, 3);
Or you can create a setter function in the Box class if you need to set the values later as
public void setDimensions(int length, int width, int height) {
this.length = length;
this.width = width;
this.height = height;
}
then b1.Box(12,5,3); becomes b1.setDimensions(12,5,3);

Related

Code works fine, just want to know why I don't need a set method for Perimeter and Area but for width and length

import java.util.Scanner;
public class Rectangle {
private double length, width;
Scanner scan = new Scanner(System.in);
public Rectangle(double length, double width){
this.length = length;
this.width = width;
}
public void setLength(double l){
length = l;
}
public double getLength(){
return length;
}
public void setWidth(double w){
w = width;
}
public double getWidth(){
return width;
}
public double getArea(){
return length*width;
}
public double getPerimeter(){
return ((2*length) + (2*width));`enter code here`
}
}
Why don't I need a set method for Area and Perimeter? Also does it matter if you make the code this.length = length as compared to length = l?
Think about it this way: how would you implement a setter for the perimeter or the area property?
There is no good way of doing it that would make reasonable sense to users of your class: let's say the width is 10 and the height is 7, and a call arrives to set the perimeter to 24. Would you adjust the height, the width, or both in order to satisfy the new value of the perimeter? There is no usable solution to this problem.
Area and Perimeter are so-called calculated properties, i.e. properties computed from values of settable properties. That is why neither area nor perimeter can have a setter.

New to Java: SuperClass and SubClass

I am fairly new to Java and I am learning about Inheritance. I am trying to create a subclass called BetterRectangle under the superclass Rec1.
Rec 1 gets the x and y coordinates (location) and also gets the width and height (size) of the rectangle. BetterRectangle calculates the perimeter and area of the rectangle.
I get errors in the main method. It cannot find any of the symbols (i.e. cannot find rec1.getHeight(20) symbol).
public class Rec1 {
private double x;
private double y;
private double width;
private double height;
public void setLocation(double xCord, double yCord) {
x = xCord;
y = yCord;
}
public void setSize(double h, double w) {
height = h;
width = w;
}
public double getHeight(double h) {
return height;
}
public double getWidth(double w) {
return width;
}
}
public class BetterRectangle extends Rectangle {
public BetterRectangle(int x, int y, int width, int height) {
super(x, y, width, height);
super.setLocation(x, y);
super.setSize(width, height);
}
public double calcPerimeter() {
return super.getHeight() * 2 + super.getWidth() * 2;
}
public double calcArea() {
return super.getHeight() * super.getWidth();
}
}
Look closely:
Rectangle Rec1 = new Rectangle();
Rec1.getHeight(20);
The type of Rec1 is Rectangle. But the Rectangle class doesn't have a getHeight method. Maybe you wanted this:
Rec1 rec1 = new Rectangle();
rec1.getHeight(20);
Notice that I renamed the variable to rec1, and changed its type.
class BetterRectangle is extending Rectangle in your sample code. So here BetterRectangle would be child and Rectangle would be parent. Now BetterRectangle uses super keyword to access getHeight,getWidth etc...functions. since these functions are not present in Rectangle class it is giving compilation Error.
Instead of extending Rectangle class extend Rec1 class in BetterRectangle and then run the main Class Rectangle. This should work.
Look carefully here
Rectangle BetterRectangle = new Rectangle();
Rectangle Rec1 = new Rectangle();
You are declaring variables of type Rectangle instead of your own classes. I can't see your import statements but you are likely creating types of java.awt.rectangle. You're mixing up variable types and variable names. When creating instances of your own classes it should look like this:
Rec1 mySimpleRec = new Rec1();
BetterRectangle myBetterRec = new BetterRectangle()
When declaring things put them in this order "Type variableName = new Type()" or "Class variableName = new Class()".

issues with use of this keyword in java

I am new to java and trying to understand the use of this keyword in java.As per documentation if instance and local variables have same name then local variables mask the instance variables.We use this keyword so that instance variable may not be masked by local variable.Below is the program i was writing to understand the use of this key work but even after use of this keyword instance variable is still getting masked.
class Box{
int height=5;
int length=10;
int breadth=15;
int CalcVol(){
int vol = height*breadth*length;
return vol;
}
Box(int height, int length,int breadth){
this.height = height;
length = length;
breadth = breadth;
System.out.println("height is " + height);
}
}
class MyBox{
public static void main(String args[]){
Box mybox1 = new Box(10, 20, 30);
int vol=mybox1.CalcVol();
System.out.println("volume is" + vol);
}
}
What i am thinking is that variable "height" printed in Box constructor should print 5 ie value of instance variable but its printing 10 ie the value passed as parameter.Please help me on this.
You need to add this before every field you want to access :
Box(int height, int length,int breadth){
// ...and move this statement to the beginning, otherwise this.height gets overriden.
System.out.println("height is " + this.height);
this.height = height;
this.length = length;
this.breadth = breadth;
}
Otherwise, length = length and breadth = breadth have no effect.
It is a name collision problem.
Within the constructor Box are the parameters height, length, and breadth. Those are also names of three fields within Box.
In Java, one considers member variables and block variables to be "closer" than field variables. As such, if you use the exact same name for both (as you have done), the assignment
height = height
will assign the parameter height to the exact same value it held (effectively a noop).
To avoid this issue, you will specify which height you are assigning.
this.height = height;
which is shorthand for "this class's height" or "the field height". When there is no name collision, the compiler will assume you meant the field variable; because there is nothing else with that name in the block.
As an aside, this is a really good reason to learn how to use the final keyword. Final means that the variable can be assigned once, and only once. It prevents it from being reassigned in situations you probably would never want.
For example
public Box(final int height, final int width, final int breadth) {
would then throw a compliation error upon
height = height;
because you are reassigning the value of height. Such techniques are very valuable when writing code, because they prevent you from writing something you think is a field assignment, when you really wrote a parameter assignment.
For your class:
class Box{
int height=5;
int length=10;
int breadth=15;
Box(int height, int length,int breadth){
this.height = height;
length = length;
breadth = breadth;
System.out.println("height is " + height);
}
}
When you construct Box, the following is happening:
Instance variable height is being set to the constructor parameter height
Constructor parameter length is being set to itself (not changing instance variable length)
Constructor parameter breadth is being set to itself (not changing instance variable breadth).
What you probably want to do in the constructor is set your instance variables with the values passed into the constructor like this:
Box(int height, int length,int breadth){
this.height = height;
this.length = length;
this.breadth = breadth;
}
You are performing an assignment here, which will make this.height take on the value of the parameter height.
this.height = height;
If you want to print the original value of this.height, put the print above the assignment and print with this.height.
System.out.println("height was " + this.height);
More completely, your constructor should look like this. Note that you need to prefix with the this keyword on every access to any instance variable that is shadowed by a local variable.
Box(int height, int length,int breadth){
System.out.println("height was " + this.height);
this.height = height;
this.length = length;
this.breadth = breadth;
}
Rather than not understanding the usage of the this keyboard in Java, I think OP isn't understanding object oriented programming in general, seeing how he's trying to print out "5" when the value has already changed. The this keyword becomes a lot less confusing once you understand that concept.
Suppose you have your class Box, and it only has one value, height:
class Box {
// This is a instance variable, that is, each new instance of Box
// has a different height variable even if they are all equal to 5
// initially. It's a different variable in memory.
int height = 5;
// Here's our constructor that sets this instance's value of height
Box(int height){
this.height = height;
}
When you make a new Box, you are making a new Box Object - for each object the height will initially start at 5, but you are changing the height of that instance of Box in your constructor.
Box box1 = new Box(10); // Height was originally 5, but changed to 10 in the constructor
Box box2 = new Box(20); // Height was originally 5, but changed to 20 in the constructor
Box box3 = new Box(30); // Height was originally 5, but changed to 30 in the constructor
When you get to the following line of code in your original program:
System.out.println("height is " + height);
It doesn't matter if it was this.height or height, it will never return 5. You already changed the value of the instance's height in the constructor.
So then. How do we print out a default height of 5? You can't. Not with the same variable name. You have to define constants in the class (like final int HEIGHT = 5) which represent the default values for that class, or use another constructor that doesn't set those values.
class Box{
int height=5;
int length=10;
int breadth=15;
int CalcVol(){
int vol = height*breadth*length;
return vol;
}
Box() {
System.out.println("height is " + height);
}
Box(int height, int length,int breadth) {
this.height = height;
this.length = length;
this.breadth = breadth;
System.out.println("height is " + height);
}
}
class MyBox{
public static void main(String args[]){
Box mybox1 = new Box(10, 20, 30); // this will never print 5, and always 10
Box mybox2 = new Box(); // this will always print 5
}
}
However, if you move the print statement above the assignment and used this.height, like Maxim Bernard did, then it will print out 5, since we didn't change the value yet.
Box(int height, int length,int breadth) {
System.out.println("height is " + this.height); // this will print out 5
this.height = height;
this.length = length;
this.breadth = breadth;
}
If this is really confusing, rather than trying to understand Java's this keyword I suggest just reading a few articles on OOP. You'll understand then that this simply means the current instance of a class.

How to use constructor in Java

Can someone please tell me what's wrong with this simple program? I'm getting output as "0".
package myConst;
public class Doconstructor
{
int length,width;
Doconstructor(int x, int y)
{
int area;
area = length * width;
System.out.println("area ="+area);
}
}
class work
{
public static void main(String args[])
{
Doconstructor d1 = new Doconstructor(10, 15);
}
}
Doconstructor d1 = new Doconstructor(10, 15);
// you are assigning values for x and y
But
Doconstructor (int x,int y)
{
int area; // you are never use x and y values for calculation
area = length *width; // so area remain 0 since current length and width is 0
System.out.println("area ="+area);
}
You need to change your code as follows.
Doconstructor (int x,int y)
{
int area;
this.length=x;
this.width=y;
area = length *width;
System.out.println("area ="+area);
}
Edit like this:-
package myConst;
public class Doconstructor
{
int length,width;
Doconstructor(int x, int y)
{
int area;
this.length=x;//Using this for current object
this.width=y;//Using this for current object
area = length * width;
System.out.println("area ="+area);
}
}
class work
{
public static void main(String args[])
{
Doconstructor d1 = new Doconstructor(10, 15);
}
}
Your output will be:
area =150
Must read this :
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
You are not setting the values of length and width and by default they are both 0. You might have to do this:
Doconstructor(int x, int y){
int area;
area = x * y;
length = x;
width = y;
System.out.println("Area = "+area);
}
You're not using the variable values you pass to the constructor in it but rather the length and width values that have been initialized to 0. You want area = x * y; instead.
The length and width fields are implicitly initialized to 0. Multiply them and you get 0.
I think what you want is
length = y ;
width = x ;
int area = length * width ;
System.out.println("area ="+area);
You have this:
public class Doconstructor {
int length,width;
Doconstructor (int x,int y)
{
int area;
area = length *width;
System.out.println("area ="+area);
}
}
At no point do you set length or width equal to anything. Their initial values are 0 and your program is doing precisely what you told it to do. area = length * width = 0 * 0 = 0.
You also are not doing anything with the x or y that you passed to the constructor, but this probably was not your intention. When writing programs, you basically need to clearly instruct the computer to do what you want to do. It's not going to guess what you want. If you ignore x and y, and don't assign any values to length or width, then that is precisely what will happen and you cannot be surprised when you see the results you see.
you are writing int length,width at class level so length and width are set to 0 as default.
After that in the constructor you are not setting any values to length and width so you are the values for length and width are 0.Hence area is also 0
Please check this link for list of default values
Constructors are used to create objects and to set the attributes. You are not setting the attributes in your constructor. Here is how your constructor should look like.
Doconstructor(int x, int y){
length = x;
width = y;
}
Secondly you are mixing the logic of a constructor and a method. You are doing the calculation of area, which seems to be a perfect fit for another method in your class. so better move that logic in a separate method:
public int calculateArea() {
int area;
area = x * y;
return area;
}
Finally create an object using constructor to set the attributes length and width. And then call calculateArea method to do the business logic of calculating area.
public static void main(String args[]){
Doconstructor d1 = new Doconstructor(10, 15); // create object and set length & width
d1.calculateArea();
}
you are not assigning the value of x and y to the variables width and length. The default value of width and length are (int) 0. Thats why you are getting the output (0*0=0). First assign the values to the variables or use "area=x*y;" .

Error using Java Classes/Inheritence

I'm having trouble with fixing this error. Can someone please help? My prompt and the code is posted below.
Write a super class encapsulating a rectangle. A rectangle has two attributes representing the width and the height of the rectangle. It has methods returning the perimeter and the area of the rectangle. This class has a subclass, encapsulating a parallelepiped, or box. A parallelepiped has a rectangle as its base, and another attribute, its length. It has two methods that calculate and return its area and volume. You also need to include a client class to test these two classes.
public class Rectangle1
{
protected double width;
protected double height;
public Rectangle1(double width, double height){
this.width = width;
this.height = height;
}
public double getWidth(){
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight(){
return height;
}
public void setHeight(double height){
this.height = height;
}
public double getArea(){
return width * height;
}
public double getPerimeter(){
return 2 * (width + height);
}
}
public class Box extends Rectangle1 {
protected double length;
public Box(double length){
this.length = length;
}
public double getLength(){
return length;
}
public void setLength(double length){
this.length = length;
}
public double getVolume(){
return width * height * length;
}
}
public class TestRectangle {
public static void main(String[] args) {
Rectangle1 rectangle = new Rectangle1(2,4);
Box box = new Box(5);
System.out.println("\nA rectangle " + rectangle.toString());
System.out.println("The area is " + rectangle.getArea());
System.out.println("The perimeter is " +rectangle.getPerimeter());
System.out.println("The volume is " + box.getVolume());
}
}
The error is at
public Box(double length){
this.length = length;
}
The error message in Eclipse IDE is as follows:
Implicit super constructor Rectangle1() is undefined. Must explicitly invoke another constructor.
And when I try to run it, it gives me:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Implicit super constructor Rectangle1() is undefined. Must explicitly invoke another constructor
at Box.<init>(Box.java:4)
at TestRectangle.main(TestRectangle.java:7)
Can someone please advise me on how to fix this error?
Your base class Rectangle1 has a constructor:
public Rectangle1(double width, double height) {
this.width = width;
this.height = height;
}
Because you wrote a constructor, the default no aruments constructor will not exist, so super() will not find the right constructor. You should write: super(0, 0) in your Box constructor, which will match Rectangle1 constructor.
Firstly, every subclass must call super(...) as the first statement in every constructor. This is a bit of a pain, so Java adds a call to super() at the start of any constructor that doesn't have a call to super(...). Since Rectangle1 doesn't have a constructor with no arguments, Java's attempt to call super() doesn't work and you need to add your own. Peter and Maroun covered this.
A bigger problem is that you haven't thought about what a Box is. What is a Box(5)? A Rectangle1 has a width and a height, while a Box has a width, a height and a depth. What is shape is a Box(5)? Your Box constructor should be something like
public Box (double width, double height, double depth)
{
super (width, height);
this.depth = depth;
}
In this constructor you can see that the arguments tell you everything you need to know about the Box and the call to super(height, width) takes care of delegating all the rectangle stuff to the base class.
You have to call the super class constructor which you define. The default constructor only exists when you haven't defined one.
Also you should not attempt to initialise fields which are initialised by the parent as this breaks encapsulation. I suggest you do this.
public Box(double length){
super(length, length);
}
This way you are calling a constructor in the super class you have defined and you let it set the fields it is responsible for.

Categories

Resources