Can we instantiate an abstract class?

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

    It is a well-established fact that abstract class can not be instantiated as everyone answered.

    When the program defines anonymous class, the compiler actually creates a new class with different name (has the pattern EnclosedClassName$n where n is the anonymous class number)

    So if you decompile this Java class you will find the code as below:

    my.class

    abstract class my { 
        public void mymethod() 
        { 
            System.out.print("Abstract"); 
        }
    } 
    

    poly$1.class (the generated class of the "anonymous class")

    class poly$1 extends my 
    {
    } 
    

    ploly.cass

    public class poly extends my
    {
        public static void main(String[] a)
        {
            my m = new poly.1(); // instance of poly.1 class NOT the abstract my class
    
            m.mymethod();
        }
    }
    

提交回复
热议问题