Understanding the concept of inheritance in Java

Posted by Nirmal on Stack Overflow See other posts from Stack Overflow or by Nirmal
Published on 2010-06-16T10:04:01Z Indexed on 2010/06/16 10:22 UTC
Read the original article Hit count: 284

Hello All....

I am just refreshing the oops features of the java. So, I have a little confusion regarding inheritance concept. For that I have a following sample code :

class Super{
    int index = 5;
    public void printVal(){
        System.out.println("Super");
    }
}
class Sub extends Super{
    int index = 2;
    public void printVal(){
        System.out.println("Sub");
    }
}
public class Runner {
    public static void main(String args[]){
        Super sup = new Sub();
        System.out.println(sup.index+",");
        sup.printVal();
    }
}

Now above code is giving me output as : 5,Sub.

Here, we are overriding printVal() method, so that is understandable that it is accessing child class method only.

But I could not understand why it's accessing the value of x from Super class...

Thanks in advance....

© Stack Overflow or respective owner

Related posts about java

Related posts about inheritance