issues with use of this keyword in java - 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.

Related

java object not compiled

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);

Java Box program with multiple methods and constructors

I am a beginner in programming and am having trouble with using constructors, specifically. I have to write a program for one of my labs that must consist only of:
Three instance variables – length, width and height (each of type double)
One instance variables – input (type Scanner) initialized to System.in
Default constructor (no-arg) – initialize all three instance variables to 1
Initial constructor – initialize all three instance variables
Copy constructor – copy Box
inputWidth, inputLength, and inputHeight methods that set the instance variables based on user input have not parameters and do not
return a value.
a displayDimensions method that displays the length X Width X height (separated by “X”) and does not return a value.
a calcVolume method that has no parameters and calculates the volume of the box
We also were given application BoxTest in which the output must
exactly match the following:
Default dimensions are 1.0 X 1.0 X 1.0 with volume of 1.0
Initial dimensions are 8.5 X 11.0 X 1.0 with volume of 93.5
Copied dimensions are 8.5 X 11.0 X 1.0 with volume of 93.5
Update dimensions
Enter length: 1
Enter width: 2
Enter height: 3
Updated dimensions are 1.0 X 2.0 X 3.0 with volume of 6.0
Here's my code:
import java.util.Scanner;
public class Box {
public static void main(String args[]) {
double length, width, height;
Scanner input=new Scanner(System.in);
new Box() { //
Box defaultBox=new Box();
double length = 1.0;
double width = 1.0;
double height = 1.0;
System.out.print("Default dimensions are " + length + " X " + width + " X " + height);
defaultBox.displayDimensions();
System.out.println(" with volume of "+defaultBox.calcVolume());
Box initialBox=new Box(length, width, height);
length = 8.5;
width = 11.0;
height = 1.0;
System.out.print("Initial dimensions are " + length + " X " + width + " X " + height);
initialBox.displayDimensions();
System.out.println(" with volume of "+initialBox.calcVolume());
Box copyBox=new Box(initialBox);
System.out.print("Copied dimensions are " + length + " X " + width + " X " + height);
copyBox.displayDimensions();
System.out.println(" with volume of "+copyBox.calcVolume());
System.out.println("\nUpdate dimensions");
initialBox.inputLength();
initialBox.inputWidth();
initialBox.inputHeight();
System.out.print("Updated dimensions are ");
initialBox.displayDimensions();
System.out.println(" with volume of "+initialBox.calcVolume());
}
double inputLength() {
Scanner input;
double length = input.nextDouble();
}
double inputWidth() {
Scanner input;
double width = input.nextDouble();
}
double inputHeight() {
Scanner input;
double height = input.nextDouble();
}
double displayDimensions(double length, double width, double height) {
Scanner input;
}
double calcVolume() {
}
}
What am I missing? My program will not compile and gives the error message
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, insert "Identifier (" to complete MethodHeaderName
Syntax error, insert ")" to complete MethodDeclaration
Syntax error, insert ";" to complete MethodDeclaration
Syntax error, insert "}" to complete ClassBody
at Box.main(Box.java:18)
As I said in the comments, you have put everything in main. Don't do that. As it is, your Box class is basically empty, and you are currently almost creating an anonymous sub-class in main. Your directions do not mention a main, but are pretty straight forward. You were supposed to write something like
public class Box {
// Three instance variables – length, width and height (each of type double)
private double length, width, height;
// One instance variables – input (type Scanner) initialized to System.in
private Scanner input = new Scanner(System.in);
// Default constructor (no-arg) – initialize all three instance variables to 1
public Box() {
this.length = this.width = this.height = 1;
}
// Initial constructor – initialize all three instance variables
public Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
// Copy constructor – copy Box
public Box(Box b) {
this(b.length, b.width, b.height);
}
// inputWidth, inputLength, and inputHeight methods that set the instance
// variables based on user input have not parameters and do not return a value.
public void inputWidth() {
this.width = input.nextDouble();
}
public void inputLength() {
this.length = input.nextDouble();
}
public void inputHeight() {
this.height = input.nextDouble();
}
// a displayDimensions method that displays the length X Width X height
// (separated by “X”) and does not return a value.
public void displayDimensions() {
System.out.printf("%.2fX%.2fX%.2f%n", length, width, height);
}
// a calcVolume method that has no parameters and calculates the volume of the
// box
public double calcVolume() {
return length * width * height;
}
}
Create a Java class named Package that contains the following:
Package should have three private instance variables of type double named length, width, and height.

Using toString in java can't find symbol error? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've been trying to use getters and setters along with toString and I'm having trouble seeing what the issue is with my code. I'm not sure where the problem lies exactly.
So, am i supposed to have a main? I'm unsure if thats needed or not in this situation.
Also, is there any way i could better format the "Rectangle(x, x)" It looks kinda weird the way it is at the moment.
public class Rectangle {
// DO NOT MODIFY THE INSTANCE VARIABLES
// begin instance variables
private int width;
private int height;
// end instance variables
// TODO - write your code below this comment.
// You need to do the following:
//
// 1.) Define a constructor which takes two ints
// representing the width and height, respectively.
// The constructor should set its instance variables
// equal to these values.
//
// 2.) Define a "getter" named getWidth, which returns
// the width of the rectangle.
//
// 3.) Define a "getter" named getHeight, which returns
// the height of the rectangle.
//
// 4.) Define a "setter" named setWidth, which takes
// the new width of the rectangle and sets the
// rectangle's width to that value.
//
// 5.) Define a "setter" named setHeight, which
// takes the new height of the rectangle and sets
// the rectangle's height to that value
//
// 6.) Define a toString method, which returns
// a String representation of the rectangle.
// As an example, if the width of the rectangle is
// 3 and the height of the rectangle is 4, this should
// return the String:
//
// "Rectangle(3, 4)"
//
public Rectangle(int rectWidth, int rectHeight) {
rectWidth = width;
rectHeight = height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setWidth(int rectWidth) {
width = rectWidth;
}
public void setheight(int rectHeight) {
height = rectHeight;
}
public String toString() {
return s;
}
public static void main(String[] args) {
Rectangle s = new Rectangle("Rectangle"+"("+rectWidth+",
"+rectHeight+")");
System.out.println(s);
}
}
A couple of things: your constructor was incorrect:
You need to set the instance variables for "this" object that you are creating, and you must call the constructor with the correct arguments.
ToString should be used to obtain a string representation of this particular instance of Rectangle. Try this:
public class Rectangle {
// DO NOT MODIFY THE INSTANCE VARIABLES
// begin instance variables
private int width;
private int height;
// end instance variables
// TODO - write your code below this comment.
// You need to do the following:
//
// 1.) Define a constructor which takes two ints
// representing the width and height, respectively.
// The constructor should set its instance variables
// equal to these values.
//
// 2.) Define a "getter" named getWidth, which returns
// the width of the rectangle.
//
// 3.) Define a "getter" named getHeight, which returns
// the height of the rectangle.
//
// 4.) Define a "setter" named setWidth, which takes
// the new width of the rectangle and sets the
// rectangle's width to that value.
//
// 5.) Define a "setter" named setHeight, which
// takes the new height of the rectangle and sets
// the rectangle's height to that value
//
// 6.) Define a toString method, which returns
// a String representation of the rectangle.
// As an example, if the width of the rectangle is
// 3 and the height of the rectangle is 4, this should
// return the String:
//
// "Rectangle(3, 4)"
//
public Rectangle(int rectWidth, int rectHeight) {
// "this" refers to the instance of Rectangle you are creating
// so this objects width and height are set to the values passed into the constructor...
this.width = rectWidth;
this.height = rectHeight;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setWidth(int rectWidth) {
width = rectWidth;
}
public void setheight(int rectHeight) {
height = rectHeight;
}
public String toString() {
// the toString returns a string representation for "this" object
return "Rectangle(" + this.width + "," + this.height + ")";
}
public static void main(String[] args) {
Rectangle s = new Rectangle(5,4);
System.out.println(s);
}
}

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