Can we instantiate an abstract class?

后端 未结 16 1386
长情又很酷
长情又很酷 2020-11-22 07:43

During one of my interview, I was asked \"If we can instantiate an abstract class?\"

My reply was \"No. we can\'t\". But, interviewer told me \"Wrong, we can.\"

16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 08:34

    No, we can't create the object of abstract class, but create the reference variable of the abstract class. The reference variable is used to refer to the objects of derived classes (Sub classes of Abstract class)

    Here is the example that illustrates this concept

    abstract class Figure { 
    
        double dim1; 
    
        double dim2; 
    
        Figure(double a, double b) { 
    
            dim1 = a; 
    
            dim2 = b; 
    
        } 
    
        // area is now an abstract method 
    
        abstract double area(); 
    
        }
    
    
        class Rectangle extends Figure { 
            Rectangle(double a, double b) { 
            super(a, b); 
        } 
        // override area for rectangle 
        double area() { 
            System.out.println("Inside Area for Rectangle."); 
            return dim1 * dim2; 
        } 
    }
    
    class Triangle extends Figure { 
        Triangle(double a, double b) { 
            super(a, b); 
        } 
        // override area for right triangle 
        double area() { 
            System.out.println("Inside Area for Triangle."); 
            return dim1 * dim2 / 2; 
        } 
    }
    
    class AbstractAreas { 
        public static void main(String args[]) { 
            // Figure f = new Figure(10, 10); // illegal now 
            Rectangle r = new Rectangle(9, 5); 
            Triangle t = new Triangle(10, 8); 
            Figure figref; // this is OK, no object is created 
            figref = r; 
            System.out.println("Area is " + figref.area()); 
            figref = t; 
            System.out.println("Area is " + figref.area()); 
        } 
    }
    

    Here we see that we cannot create the object of type Figure but we can create a reference variable of type Figure. Here we created a reference variable of type Figure and Figure Class reference variable is used to refer to the objects of Class Rectangle and Triangle.

提交回复
热议问题