views:

211

answers:

4

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

+9  A: 

This is called instance variable hiding - link. Basically you have two separate variables and since the type of the reference is Super it will use the index variable from Super.

Petar Minchev
Damn, was just about to write the same sentence :-).
Helper Method
+4  A: 

Objects have types, and variables have types. Because you put:

Super sup = new Sub();

Now you have a variable sup of type Super which refers to an object of type Sub.

When you call a method on an object, the method that runs is chosen based on the type of the object, which is why it prints "Sub" instead of "Super".

When you access a field in an object, the field is chosen based on the type of the variable, which is why you get 5.

Daniel Earwicker
+1  A: 

index is simply a field belonging to the parent class. Because it belongs to the parent class, it means that it's an attribute to all the children. To simply the concept:

A Class Animal could have a field age and a field name All sub classes would share those attributes, but would have additional field(s), which would be contained into those children classes only. For example hairColour could be the only attribute of the Dog class, but not to the class Snake, which could have a simple unique attribute venomous

In this structure all Animal have a name, and an age, which is what could define Animals in general, an each specie have some extra attribute(s) unique to them, which are contained into their respective sub classes.

Your code doesn't clearly show this, as your sub class has no constructor, indeed no super constructor call. As explained by Petar, your none private attribute index is access from the super class

Marc
+1  A: 

This happens coz functions follows runtime binding whereas variables are bound at compile time.

So the variables depend on the pointer's datatype whereas the functions depend on the value within the pointer' datatype.

dev ray
Can you exaplain where is pointer in java
hib