Inheritance in Java

 

Corejava InheritanceNotes

coding-zon-java-inheritance



 

 

 

 


 
 

 Table of contents

 
 
 
 

Inheritance in Java

 

Definiation: 

Inheritance is one of the key features of Object-oriented programming. It is the mechanism in java which allows us to create a new class (derived class) from an existing class (base class).

 Java supports different types of inheritance. The main types of inheritance those Java supports are as follows:

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance:
  4. Multiple Inheritance (using Interfaces)


 

1. Single Inheritance:

Derived class inherits the features (attributes and methods) from the base class and can have additional features of its own.

The keyword extends used to inherit from one class to other.  

 
 

Creating Inheritance in Java

The general syntax for creating inheritance is as show below:

class Base{
 // Base class code
}
class Derived extends Base{
 // Derived class code
}
 
 
Example:
 
class A{
void m1(){
	System.out.print ("m1");
}
}
class B extends A{
void m2(){
	System.out.print ("m2");
}
}
class Test{
public static void main(String args){
	A aob= new A();
	B aob = new B();
	aob.m1();
	bob.m2();

             bob.m1(); // inherited from A 

}


 

 

 

Super  keyword

 

In inheritance constructors are not inherited. but they can be accessed by derived classes.

 

super keyword used to invoke base class constructor from the derived class, to pass parameters from the child constructor to parent constructor.

 
Example:
 

class A
    int x;
A(int x)
{
    this.x=x;
}
void area() 
{ 
    int asq = x * x;
    System.out.println(asq);
}
} 
class B extends A
    int y,z;
B(int i, int j, int k ) { 
    super(i); //invokes A's constructor and (i is passed to x) 
    y = j; 
    z = k;
}
area() {
    int ar = y * z; 
    System.out.println(ar); 
	}	

 }
 
 

In the above, ex. B  invoking super class constructor and passing value i to x. 


 

 2. Multilevel Inheritance:


In multilevel inheritance, a class is derived from another class, which itself is also a subclass of another class.

 

 

 

class A{
void m1(){
	System.out.print ("m1");
}
}
class B extends A{
void m2(){
	System.out.print ("m2");
}
}
class C extends B{ 
void m3(){
	System.out.print ("m3");
} 
public static void main(String args){
	A aob= new A();
	B bob = new B();
      C cob = new C(); 
        aob.m1();
	  bob.m2();
        bob.m1();  // inherited from A 
           
        cob.m1(); // inherited from A 
        cob.m2(); // inherited from B 
        cob.m3(); // its own  

}

}

 

3. Hierarchical Inheritance:

In hierarchical inheritance, there are multiple derived classes inherit from a single baseclass.

 

 

class A{
void m1(){
	System.out.print ("m1");
}
}
class B extends A{
void m2(){
	System.out.print ("m2");
}
}
class C extends A{
void m3(){
	System.out.print ("m3");
} 
public static void main(String args){
	A aob = new A();
	B bob = new B();
      C cob = new C(); 
 
        aob.m1();
	  bob.m2();
        bob.m1();  // inherited from A 
           
        cob.m1(); // inherited from A       
        cob.m3(); // its own  

}

}

 


In the above, ex. B can be extended only one class

It cannot be extended by more than one class, Ex: class C extends A, B //not allowed  

Multiple inheritance can be achieved by Interfaces.

 

 

 


4. Multiple Inheritance (Using Interfaces):

Java does not support multiple inheritance, but it allows multiple inheritance through interfaces. A single class can implement multiple interfaces.
 

 

 

 

 Interfaces in Java

 
 



Interface contains only method declarations(empty methods). 

These methods are implemented by other classes.

Example

Interface declaration

interface Iface1{
 
 public void m1();
 public void m2();
 public void m3(); 
 
}

 

Interface implementation

 

Example:
 
interface Iface1{

 public void m1();
 public void m2();
 public void m3();
}
class A implements Iface1{
public void m1(){
 System.out.println("m1"); 
 
}
public void m2()
{ 
 System.out.println("m2"); 
}
public void m3()
{ 
 System.out.println("m3"); 
}
 public static void main(String args{})
 
 A aobj = new A();  
 
aobj.m1();  
aobj.m2();  
aobj.m3();
} 

 }
 
 
 
 
Example2: 

 

Interface can have properties.  These mostly constants initialized in interface itself. and shared by all implemented classes. Generally all methods and properties are public.

 

Implementing multiple interfaces 

 
interface Iface1
{ 
 public const String v1 = "value1"; 
 public void m1(); 
}
interface Iface2{ 
  public const String v2 = "value2"; 
  public void m2(); 
}
class A implements Iface1,Iface2 {
 public void m1(){
System.out.println("v1 "+v1 ); 
}
public void m2()
 System.out.println("v2 "+v2 ); 
}
 
 
public static void main(String args{})  
 
    A aobj = new A(); 
 
    aobj.m1(); 
    aobj.m2();  
  
} 

 }
 

 

Example3

interface Shape{
 
 void area();
}
 
class square implements Shape { area(){.... }
}
class Rect implements Shape { area(){.... }
}
class Circle implements Shape { area(){.... }
}

-- in the above example, area() is common in all classes(Square, Rect, Circle).

 Uses of Interfaces: 

To achieve commonality, i.e. to maintain some standard among different classes, interfaces are used. 

code reusability.


 

Rule for implementing interfaces

  • All Methods must be defined in the implementation class.
  • If not defined all methods, then that class becomes abstract. (means not complete) this class can't be instantiated. So this class must be extended by some other class which implements all remaining methods of interface.
  • Then this child class called as Concrete Class (this class can be instantiated).
  • Abstract classes extended by some other classes

 

 

Abstract class in Java

 
  • Abstract class begin with abstract keyword
  • Abstract class contains some methods undefined.
  • Abstract class can't be instantiated. 
  • Abstract methods starts with keyword abstract.
 
 General Sytax of the abstract class:
 
abstract class A 
 
abstract public void m1();  // method declaration. 
 
public void  m2() // method defination. 
.......; 
.......; 
 

-- m1()  // not defined just it is declared.

-- extended class will provides definition for method declarations.

 
General Syntax of the abstract class extending by derived class:

 

class B extend by A and provided m1 method body.

 
class B extends A
{
public void m1();  // A's Method defined
{
.......; 
}
public void m3()  // B's own method.
{ 
.......; 
}
}

 

Concrete class

The class  which defines all the methods of its parents is called Concrete  class . Concrete class can be instantiated. In the above example,  class B can be concrete class.

 Example:

class B extends A{
public void m1() // A's Method defined 
.......; 
}
public void m3() // B's own method.
.......;
}
public static void main(String args{})
B b= new B(); 
b.m1();   // A's Method defined 
b.m2();   // A's m2 method 
b.m3();  // B's Method m3
} 

Overriding in Java Inheritance

 Base class method is redefined in the derived class.

Rules:  
  • Both methods should have same signature i.e., both method name, parameters list should be same. 
  • return type can be different. 
  • method which is invoked depends on the object created.
 General Syntax for method overriding

class Animal{
	eat() {
	s.o.p("eats something"); }
class Horse extends Animal { 

eat(){
	s.o.p("oates"); }
	}	
 }
 
class OverrideDemo{
 
public static void main(String args[]) { 

Animal a= new Animal();// o/p -->something 

Animal b= new Horse();// o/p -->oates 

a.eat(); 

b.eat(); 

}}
 
 
Program: 
 
public class Animal{
void eat() {
System.out.println("eats something"); 
} 
}
class Horse extends Animal { 
void eat(){ 
System.out.println("eats oates");
}
}
class OverrideDemo{
public static void main(String args[]) 
{ 
Animal a= new Animal();//-----> o/p -->eats something 
		
Animal b= new Horse();//-----> o/p -->eats oates
a.eat(); 
		
b.eat(); 
}
}
	

 

Menu

Dynamic Binding vs static binding in Java

Static binding

Reference points to its own type of object.

Rect rt = new Rect(); 

 

Dynamic binding

It is super type of reference, points to any of its child object  

Example: 

Shape sp;   //super class ref.

sp = new Square();  //or

sp = new Rect();   //or

sp = new Circle(); 

sp = rt   // assigning Rect ref to its super class ref

 
Example:
 
interface Shape{
	public void area();
}
class square implements Shape { 
	public void area(){
	System.out.println("area of Square");
	}
	}
class Rect implements Shape 
{ 
	public void area(){
	System.out.println("area of Rect"); 
	}
}
class Circle implements Shape 
     public void area(){
         System.out.println("area of Circle");
         }
}
class Test{
	Shape sp; 
	Square sq= new Square(); 
	sq.area();
	Rect rt = new Rect();//static binding occurs at compile time[compiler] 
	rt.area(); 
	Circle cr= new Circle(); 
	cr.area();
	sp=rt; sp.area(); //Dynamic Binding occurs at runtime[jvm]
}
}	
 
 
 
Program:
 

interface Shape{
	public float area();
}
class Square implements Shape { 
	int side;
	Square(int side) 
	{  
        this.side=side;
	}
	public float area(){
		return (side*side);
	}
}
class Rect implements Shape 
{ 
	int side; 
int width;
	Rect(int side, int width)
	{  
		this.side=side; 
		this.width=width; 
	}
	public float area()
	{ 
		return (side*width);
	}
}
class Circle implements Shape 
{ 
	public final float pi=3.14f; 
	int r; 
	Circle(int r)
	{ 
		this.r=r; 
	}
	public float area(){
		return (2*pi*r*r); 
	}
}
class Test1{ 
 
public static void main(String args[]){ 
 
       float area = 0.0f; 
	Square sq = new Square(4); 
	area = sq.area();
	System.out.println("Square Area="+area); 
 
       Rect rt = new Rect(5,8); 
	area = rt.area();
	System.out.println("RectangleArea="+area); 
 
       Circle cr = new Circle(5); 
	area = cr.area();
	System.out.println("Circle Area="+area); Shape sp; 
 
       sp = sq; 
	area = sp.area(); //Dynamic Binding occurs at runtime[jvm]
	System.out.println("Area="+area); 
}
} 

 

 

 

 

Types of inheritance in Java 

coding-zon-types-of-interitance-in-Java

Extends Vs implements


coding-zon-java-extend-vs-implementation



 Java Tutorial Home

 

Comments

Popular posts from this blog

Shoppingcart using PHP Sessions - Miniproject

Import CSV File Into MySQL Using PHP

Export Data to Excel with PHP and MySQL