I'm learning Java using Sams Teach Yourself Java in 21 days (btw this is taking me much longer than 21 days). In chapter 5, the final exercise asks me to create a class FourDPoint which is a subclass of Point. I did this, but had an interesting result. The first time I did the exercise this was my code:
import java.awt.Point;
class FourDPoint extends Point {
int x;
int y;
int z;
int t;
FourDPoint(int x, int y, int z, int t){
super(x, y);
this.z = z;
this.t = t;
}
public static void main(String[] arguments){
FourDPoint fp = new FourDPoint(5, 5, 10, 10);
System.out.println("x is " + fp.x);
System.out.println("y is " + fp.y);
System.out.println("z is " + fp.z);
System.out.println("t is " + fp.t);
}
}
The result: x is 0, y is 0, z is 10, y is 10.
I changed my code by eliminating the intitilized x and y, which gave me the correct answer. My question: why did I get x is 0 and y is 0? Do the intitiaized x and y take precedence over the super(x, y)?
This is what we call hiding. Assuming your class Point
also declares two instance variables named x
and y
, those are the ones you are setting with
super(x, y);
However, when you reference
System.out.println("x is " + fp.x);
System.out.println("y is " + fp.y);
you are referring to the members declared in FourDPoint
. Those haven't been initialized by you, so they default to 0.
On a related note, polymorphism does not apply to instance variables. Instead, the member is resolved according to the type of the reference on which you accessed it.
So
FourDPoint fp = ...;
fp.x;
fp.x
would refer to the x
member declared in FourDPoint
. But
FourDPoint fp = ...;
fp.x;
((Point) fp).x;
((Point) fp).x;
would refer to the x
member declared in Point
.
In your subclass, you shadow Points x and y variables with your own. To fix this, you can either remove your x and y (You don't use them) or reference Points ones using super.x
and super.y
When you call super() in the constructor, Point sets its x and y fields. You created an x and y yourself that get defaulted to 0. So when you reference fp.x and fp.y, you will always get your ones (which are always 0)
Your class FourDPoint
contains local members that shadow the super Point x
and y
, comment out these two lines -
// int x;
// int y;
You never set the values of x
and y
to something, so they will always return 0.
Yes, you call the super constructor but this doesn't matter: even if there are variables x
and y
in Point
, they are hidden by the variables named the same in FourDPoint
.
Not to mention that the variables in Point
should have been protected
as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With