In the following code example:
class Parent {
int x =5;
public Integer aMethod(){
System.out.print("Parent.aMthod ");
return x;
}
}
class Child extends Parent {
int x =6;
public Integer aMethod(){
System.out.print("Child.aMthod ");
return x;
}
}
class ZiggyTest2{
public static void main(String[] args){
Parent p = new Child();
Child c = new Child();
System.out.println(p.x + " " + c.x);
System.out.println(p.aMethod() + " \n");
System.out.println(c.aMethod() + " \n");
}
}
And the output:
5 6
Child.aMthod 6
Child.aMthod 6
Why does p.aMethod()
not print 6 when p.x prints 6?
Thanks
Oops a slight typo: The question should be "why does p.aMethod() not print 5 when p.x print 5" - Thanks @thinksteep
Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name.
Private Members in a SuperclassA subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
If the superclass and the subclass have instance variable of same name, if you access it using the subclass object, the subclass field hides the superclass's field irrespective of the types. This mechanism is known as field hiding.
A class in Java can be declared as a subclass of another class using the extends keyword. A subclass inherits variables and methods from its superclass and can use them as if they were declared within the subclass itself: class Animal { float weight ; ... void eat () { ... } ... }
There's no polymorphic resolution being done when you access class member fields (instance variables) like p.x
. In other words, you'll get the results from the class that's known at compile time, not what is known at run time.
For method calls this is different. They are dispatched at run time to an object of the actual class the reference points to, even if the reference itself has a super type. (in the VM this happens via the invokevirtual
opcode, see e.g. http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html#invokevirtual).
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