Example code:
public class A {
public int number;
public A(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
public class B extends A{
public int number;
public B(int number) {
super(number);
}
public int getNumber() {
return number;
}
}
public class C {
public static void main(String args[]) {
A test1 = new B(2);
B test2 = new B(2);
System.out.println(test1.number) // prints 2
System.out.println(test2.number) // prints 0
System.out.println(test1.getNumber()) //prints 0
System.out.println(test2.getNumber()) // prints 0
}
}
As shown above test1.number is not equal to test1.getNumber().
So when I make test1 an object of type A test1.number is referring to the int number in class A.
But when I call test1.getNumber() it's calling getNumber() in class B?
Why does that happen?
All methods in Java are virtual. I'll get to what that means in a second.
So, on this line:
A test1 = new B(2);
You've assigned a new instance of class B
to a variable declared as holding an A
.
When you use test1.number
, you're using the number
variable declared in class A
, which given that the constructor for B
calls super(number)
will be 2.
However, when you call test1.getNumber()
, that's where the virtual kicks in. Virtual means that it will always call a method in the constructed class rather than the type of variable that you've declared it as. In other words, rather than calling A
's getNumber
like you thought it would, it actually call's B
's getNumber
instead. B
's constructor doesn't assign a value to B
's number
variable, so you get 0.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments