Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inheritance and late binding, why does int id have the parent class value and not the child class one?

Determine the output:

public class Test1{
    public static void main(String args[]){
        ChildClass c = new ChildClass();
        c.print();
    }
}

class ParentClass{
    int id = 1;
    void print(){
       System.out.println(id);
    }
}

class ChildClass extends ParentClass{
    int id = 2;
}

I know that the answer is 1, and I'm guessing that it's because since the print function isn't overridden in the ChildClass, it has the same definition as it has in the ParentClass. Why isn't the ID the one given in child class since Java uses late binding?

like image 328
drossy11 Avatar asked Feb 15 '16 15:02

drossy11


People also ask

Can a parent class access child class in Java?

The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.

Why do we assign a parent reference to the child object in Java?

The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.

Can parent class inherit the properties of child class in Java?

In Java inheritance we can access parent class properties via the child class object, as there is a keyword extends for achieving inheritance.

What is parent class and child class in Java?

The class which inherits the properties of other is known as child class (derived class, sub class) and the class whose properties are inherited is known as parent class (base class, superclass class).


1 Answers

There is no dynamic dispatch on object fields, only on methods.

like image 158
cadrian Avatar answered Oct 04 '22 17:10

cadrian