Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java inheritance

Why does is print last "I'm a Child Class." ?

public class Parent
{
    String parentString;
    public Parent()
    {
        System.out.println("Parent Constructor.");
    }

    public Parent(String myString)
    {
        parentString = myString;
        System.out.println(parentString);
    }

    public void print()
    {
       System.out.println("I'm a Parent Class.");
    }
} 

public class Child extends Parent
{
    public Child() {
        super("From Derived");
        System.out.println("Child Constructor.");
    }

    public void print()
    {
       super.print();
       System.out.println("I'm a Child Class.");
    }

    public static void main(String[] args)
    {
        Child child = new Child();
        child.print();
        ((Parent)child).print();
    }
}

Output:

From Derived

Child Constructor.

I'm a Parent Class.

I'm a Child Class.

I'm a Parent Class.

I'm a Child Class.
like image 336
vad Avatar asked Aug 17 '10 19:08

vad


People also ask

What are the 4 types of inheritance in Java?

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

What is the inheritance in Java?

Inheritance in Java is a concept that acquires the properties from one class to other classes; for example, the relationship between father and son. Inheritance in Java is a process of acquiring all the behaviours of a parent object.

What are the 6 types of inheritance in Java?

Core Java bootcamp program with Hands on practice Single Level inheritance - A class inherits properties from a single class. For example, Class B inherits Class A. Hierarchical inheritance - Multiple classes inherits properties from a single class. For example, Class B inherits Class A and Class C inherits Class A.


1 Answers

Because this is an example of polymorphism (late binding). At compile time you specify that the object is of type Parent and therefore can call only methods defined in Parent. But at runtime, when the "binding" happens, the method is called on the object, which is of type Child no matter how it is referenced in the code.

The part that surprises you is why the overriding method should be called at runtime. In Java (unlike C# and C++) all methods are virtual and hence the overriding method is called. See this example to understand the difference.

like image 150
Bozho Avatar answered Sep 28 '22 00:09

Bozho