Saturday 13 January 2018

4.10 Inheritance

Inheritance - When one class(subclass) acquires the properties of other class (Super class) is called inheritance.

Syntax:

class SuperClass {
   .....
   .....
}
class SubClass extends SuperClass {
   .....
   .....
}


Multiple Inheritance in java is possible using Interface.

class A extends B, C not allowed
class A extends B implements C


super() is by default in every constructor first line but it is hidden.
When you create the object of subclass, because of super() method ,it will first call the default constructor of super class .




class A
{
public A()
{
System.out.println(" Default Constructor of A");
}

public A(int n)
{
System.out.println(" Parameterized Constructor of A");
}
}

class B extends A
{
public B()
{
System.out.println(" Default Constructor of B");
}

public B(int n)
{
//super(3);
//Parametrised Constructor of A
//Parametrised Constructor of B

System.out.println(" Parametrised Constructor of B");
}
}

class superdemo
{
public static void main(String args[])
{
A obj1=new A(); 
//Default Constructor of A

A obj2=new A(5); 
//Parametrised Constructor of A

B obj3=new B();
//Default Constructor of A
//Default Constructor of B

B obj4=new B(1);
//Default Constructor of A
//Parametrised Constructor of B

A obj5=new B(); // A type of reference for object of B class
//B obj6=new A(); superdemo.java:50: error: incompatible types: A cannot be converted to B
}

}

No comments:

Post a Comment