Reputation: 1
This concept contradicts the concept of a class
and it's instance.
Below is the program that looks fine to me and gives NullPointerException
as expected:
class SuperClass{
int x = 2;
}
class SubClass extends SuperClass{
int x = 4;
}
public class Dummy2 {
public static void main(String[] args){
SubClass obj1 = new SubClass();
SuperClass obj2 = null;
System.out.println(obj1.x);
System.out.println(obj2.x);
}
}
But when I say SuperClass obj2 = obj1;
strangely I see the value of SuperClass
instance member value 2
,
despite there is no instance of class SuperClass
created in the above program.
Is this the valid concept in Java?
Upvotes: 0
Views: 116
Reputation: 4435
First, since obj2
is null
in your example, it will of course throw a NPE when you attempt to access x
in it.
Second, when you set obj2 = obj1
, you are casting obj1
, of type SubClass
, to type SuperClass
. When you then access x
in obj2
, you are accessing the x
that SuperClass
knows about, which has a value of 2
. This is how it is supposed to work.
The reason is, the x
in SubClass
isn't overwriting the x
in SuperClass
. It is simply hiding it. So when obj1
is cast to type SuperClass
, the x
in SuperClass
is now the visible x
.
If you wish to get the x
value that you seem to be expecting, simply use a getter instead of accessing x directly, and then you can override it in SubClass
.
SuperClass:
public class SuperClass {
public int x = 2;
public int getX() {
return x;
}
}
SubClass:
public class SubClass extends SuperClass {
public int x = 4;
public int getX() {
return x;
}
}
test code:
SubClass obj1 = new SubClass();
SuperClass obj2 = obj1;
System.out.println(obj2.x); // outputs 2
System.out.println(obj2.getX()); // outputs 4
Upvotes: 7
Reputation:
It's valid in java, and many other languages strongly typed. When you upcast the variable to a superclass you can use properties of that class only. This make a variable strongly typed. Means that you have a variable of the type that you can use regardless of instance type. The type of variable is important that you have access to.
Upvotes: 0