Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hidden fields though inheritance

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

Edit

Oops a slight typo: The question should be "why does p.aMethod() not print 5 when p.x print 5" - Thanks @thinksteep

like image 948
ziggy Avatar asked Dec 27 '11 17:12

ziggy


People also ask

What is hiding fields?

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.

Are private fields inherited Java?

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.

How to hide fields in Java?

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.

Do subclasses inherit methods?

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 () { ... } ... }


1 Answers

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

like image 148
Arjan Tijms Avatar answered Sep 19 '22 16:09

Arjan Tijms