Thursday, 24 July 2014

Can an abstract class have constructor ?

An abstracts class is a class which is incomplete, since it has abstract methods, which don't have implementation. Abstract class can have a constructor. It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation expression. You can instantiate an abstract class using Anonymous classes.


If class A is abstract and class B extends A, instantiation of class B calls A's constructor first, next B's.

public abstract class A {
    abstract void print();
    
    A(){
        System.out.println("I am in A");
    }
}

public class B extends A{
    
    @Override
    void print(){
        
    }
    
    B(){
        System.out.println("I am in B");
    }
    
    public static void main(String args[]){
        B obj = new B();
    }
}

Output
I am in A
I am in B



                                                             Home

No comments:

Post a Comment