Can we instantiate an abstract class?

后端 未结 16 1164
长情又很酷
长情又很酷 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:26

    = my() {}; means that there's an anonymous implementation, not simple instantiation of an object, which should have been : = my(). You can never instantiate an abstract class.

    0 讨论(0)
  • 2020-11-22 08:29

    No, you can't instantite an abstract class.We instantiate only anonymous class.In abstract class we declare abstract methods and define concrete methods only.

    0 讨论(0)
  • 2020-11-22 08:32

    You can say:
    we can't instantiate an abstract class, but we can use new keyword to create an anonymous class instance by just adding {} as implement body at the the end of the abstract class.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题