views:

116

answers:

4
+9  Q: 

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.
+13  A: 

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.

Bozho
Good Question and good answer. This is also a good thing in real programs; your code could break if you by accident had some code that called the parent implementation.
Tormod
+1  A: 

Both:

child.print();

and

((Parent)child).print();

Should return:

I'm a Parent Class.
I'm a Child Class.

In that order.

Casting an object to its base class doesn't change which method call gets made.

In this case, even after the cast, the child print method gets called and not the parent.

vicjugador
What confused me was that the same code in C# prints only "I'm Parent Class"
vad
A: 

Even though you cast child to Parent this does not change its implementation of the method. This does not actually make it a parent. This is why you can do something like:

Image img = new BufferedImage(...);

Even though Image is abstract img is still a bufferedImage underneath.

Jeff
A: 

Even though you are casting it as the Parent class, that does not mean it will use its parent's functions-- it will only treat the object as a Parent.

By saying ((Parent)child).print(); you are saying "Treat this object as a Parent Object, Not a Child Object". Not "Use the parent method implementations"

Thus if the child object had other methods you wouldn't be able to call them. But since print() is a method of the parent you can still call it, but it uses the actual object's (not the class its casted to) implementation.

Zugwalt