Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the concept of inheritance in Java

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

like image 781
Nirmal Avatar asked Jun 16 '10 10:06

Nirmal


People also ask

What is the concept of inheritance in Java?

Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, inheritance means creating new classes based on existing ones.

What does the concept of inheritance explain?

Inheritance is the process by which genetic information is passed on from parent to child. This is why members of the same family tend to have similar characteristics.

What are the 4 types of inheritance in Java?

Types of Inheritance in Java: Single, Multiple, Multilevel & Hybrid.


2 Answers

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.

like image 103
Petar Minchev Avatar answered Sep 23 '22 01:09

Petar Minchev


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.

like image 29
Daniel Earwicker Avatar answered Sep 24 '22 01:09

Daniel Earwicker