Inheritance in JAVA

Inheritance is the process of obtaining the data members and methods from one class to another class. It is one of the fundamental features of object-oriented programming as we learned.

Syntax :

class Subclass/Parentclass-Name extends Superclass/Childclass-Name  
{  
   //methods and Data  
}
  • In the inheritance, the class which gives data members and methods is known as base or super or parent class.
  • The class which takes the data members and methods is known as the sub or derived or child class.

Inheritance is Mainly used for CODE re usability by putting the code public in the parent class, and later when it needed it can be derived. Its main uses are to enable polymorphism and to be able to reuse code for different classes by putting it in a common

It also enables polymorphism by overriding the method and to be able to reuse code for different classes by putting it in a common superclass.

In Real Life, If we take an example of our parents then they are the superclass and we are the child class because we derive or inherit all properties of our parents.

inheritance.png

Example:

class Parent{ 
void parentEat(){System.out.println("Parents eating...");} 
} 
class child extends Parent{ 
void childEat(){System.out.println("Child eating...");} 
} 
class TestInheritance{ 
public static void main(String args[]){ 
Dog child = new child(); 
c.parentEat(); 
c.childEat(); 
}
}

Output:

Parents eating...
Child eating...

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: