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.
Types of Inheritance in Java: Single, Multiple, Multilevel & Hybrid.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With