Search code examples
javainheritancedata-hiding

Java - inheritance


class Base
{
        int x=1;
    void show()
    {
        System.out.println(x);
    }
}
class Child extends Base
{
    int x=2;
    public static void main(String s[])
    {
        Child c=new Child();
        c.show();
    }
}

OUTPUT is 1. The method show is inherited in Base class but priority should be given to local variable and hence the output should have been 2 or is it that the compiler implicitly prefixes super before it??


Solution

  • Since you are not overriding the show method in Child, the Base's version will be used. Therefore it cannot see the x variable you defined in Child. Your IDE (if you are using one) should give you a warning that you are "hiding a field".

    You can achieve the expected functionality by setting the x of a Child object after instantiating it. Try:

    class Base
    {
        int x = 1;
    
        void show() {        
            System.out.println(x);
        }
    }
    
    class Child extends Base
    {
        public static void main(String s[]) {
    
            Child c = new Child();
    
            c.show();
            c.x = 2;
            c.show();
        }     
    }
    

    This should yield 1 and then 2.

    EDIT: Note this works only when the x field is accessible from the main function.