Pageviews

Thursday 13 June 2013

Inheritance in Java

by Unknown  |  in Object Oriented Programming at  Thursday, June 13, 2013

Inheritance is the another powerful feature provided by Object Oriented Programming.It is the process of inheriting features from one class to the other.The class from which features are inherited is known as Base Class/Super Class/Parent class.The class which inherits the features is known as Derived class/Sub Class/Child class.The derived class consists of features of base class as well as its own features.

Most of us gets confused with the types of Inheritance,so here is the simple way to learn the types of Inheritance.In Java,we use 'extends' keyword when a class inherits features of another class.Lets take an example;

class derived extends base  //This means that derived class inherits base class features.

Java supports 3 types of Inheritance,i.e.


  • Single level Inheritance.
  • Multi-level Inheritance.
  • Hierarchical Inheritance


Single level Inheritance:In single level inheritance single Derived class inherits the features of Base class.In this post only single level inheritance is discussed,the other two types  will be explained in the next post.



As the above diagram shows Class A is the base class and it is derived by the Class B.Here is the simple example of a program to show the use of single level inheritance.

WAP to implement Single level Inheritance:

import java.util.*;
class base{                                                                              //Base class declared
void add()
{
Scanner input=new Scanner(System.in);
System.out.println("Enter first number");
int a= input.nextInt();
System.out.println("Enter Second number");
int b= input.nextInt();

int s;
s=a+b;
System.out.println("Your result  is"+s);
}
}
class inherit extends base{                                                         //Derived class inherits base class
public static void main(String args[]){
base b=new base();
b.add();
}
}

The output goes here:

Inheritance






0 comments:

Proudly Powered by Blogger.