Java Basics – Parent and Child Class

Suppose we have two Classes, a Parent and a Child Class

public class Parent {

	public void print(){
		System.out.println("Parent Print");
	}
}

public class Child extends Parent{

	public void print(){
		System.out.println("Child Print");
	}
}

When we create this code, what would be the result?

		
Parent P = new Child();
P.print();

The answer would be “Child Print”.

“P” object is created from the Child Class. Java allows to create an Object “Child” from a “Parent”. Since the “new Child()” Class is also Parent from the extends keyword , but you can’t say Child c = new Parent(); because the “new Parent()” Class does not define Child in its extends.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s