Vous êtes sur la page 1sur 4

INHERITANCE One of the fundamental mechanisms for code reuse in OOP, is inheritance.

It allow new classes to be derived from an existing class. The new class can inherit members from the oldv class.The subclass can add new behavior and properties, and under certain circumstances,modify its inherited behavior. To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. To see how, lets begin with a short example. The following program creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of A. In Java, inheritance is used for two purposes: 1. class inheritance - create a new class as an extension of another class, primarily for the purposeof code reuse. That is, the derived class inherits the public methods and public data of thebase class. Java only allows a class to have one immediate base class, i.e., single class inheritance. 2. interface inheritance - create a new class to implement the methods defined as part of an interface for the purpose of subtyping. That is a class that implements an interface conforms to (or is constrained by the type of) the interface. Java supports multiple interface inheritance. In Java, these two kinds of inheritance are made distinct by using different language syntax. For class inheritance, Java uses the keyword extends and for interface inheritance Java uses the keyword implements. public class derived-class-name extends base-class-name { // derived class methods extend and possibly override // those of the base class } public class class-name implements interface-name { // class provides an implementation for the methods // as specified by the interface

}
The following kinds of inheritance are there in java. Simple Inheritance Multilevel Inheritance

Pictorial Representation of Simple and Multilevel Inheritance

Simple Inheritance
Simple Inheritance

Multilevel Inheritance

When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single inheritance or one level inheritance. //A simple example of inheritance Class A {

int x; int y; int get(int p , int q) { x=p; y=q; return(0); } Void show(){ System.out.println(x); } }

Class B extend A{ public static void main(String arg[]){ A a=new A(); a.get(2,4); a.show(); } Void Display(){ System.out.println(B); } } PROGRAMclass abc{ public void show1(){ System.out.println("i m from abc");} } class xyz extends abc{ public void show2(){ System.out.println("i m from xyz");} } class A extends xyz{

public void show3(){ System.out.println("i m from A");} } class X{ public static void main(String arg[]){ A ob=new A(); ob.show1(); ob.show2(); ob.show3(); } } Show() Output I am from abc I am from xyz I am from x Show1() Show2() Show3() Main() CALL STACK

Vous aimerez peut-être aussi