Inheritance in java

A class can be derived from another class. In this case this class is called a subclass. Another common phrase is that a class extends another class.

The class from which the subclass is derived is called a superclass.

Inheritance allows a class to inherit the behavior and data definitions of another class.

The following codes demonstrates how a class can extend another class. In Java a class can only extend a maximum of one class.

Simple example of Inheritance

class Parent
{
    public void p1()
    {
        System.out.println("Parent method");
    }
}
public class Child extends Parent {
 public void c1()
 {
  System.out.println("Child method");
 }
 public static void main(String[] args)
 {
  Child cobj = new Child();
  cobj.c1();   //method of Child class
  cobj.p1();   //method of Parent class
    }
}

Output

Child method
Parent method

Purpose of Inheritance

  1. To promote code reuse.
  2. To use Polymorphism.

Types of Inheritance

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Heirarchical Inheritance

NOTE :Multiple inheritance is not supported in java

Why multiple inheritance is not supported in Java

  • To remove ambiguity.
  • To provide more maintainable and clear design.

super keyword

In Java, super keyword is used to refer to immediate parent class of a class. In other words super keyword is used by a subclass whenever it need to refer to its immediate super class.

Example of Child class refering Parent class property using superkeyword

class Parent
{
    String name;

}
public class Child extends Parent {
 String name;
 public void details()
 {
  super.name = "Parent";    

   //refers to parent class member
  name = "Child";
  System.out.println(super.name+" and "+name);
 }
 public static void main(String[] args)
 {
  Child cobj = new Child();
  cobj.details();
 }
}

Output

Parent and Child

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