How to create an object of an abstract class and interface

前端 未结 12 1209
旧巷少年郎
旧巷少年郎 2020-12-09 04:36

How do I create an object of an abstract class and interface? I know we can\'t instantiate an object of an abstract class directly.

12条回答
  •  粉色の甜心
    2020-12-09 05:10

    To create object of an abstract class just use new just like creating objects of other non abstract classes with just one small difference, as follows:

    package com.my.test;
    
    public abstract class MyAbstractClass {
        private String name;
    
        public MyAbstractClass(String name)
        {
            this.name = name;
        }
    
        public String getName(){
            return this.name;
        }
    
    
    }
    
    package com.my.test;
    
    public class MyTestClass {
    
        public static void main(String [] args)
        {
            MyAbstractClass ABC = new MyAbstractClass("name") {
            };
    
            System.out.println(ABC.getName());
        }
    
    }
    

    In the same way You can create an object of interface type, just as follows:

    package com.my.test;
    
    public interface MyInterface {
    
        void doSome();
        public abstract void go();
    
    }
    
    package com.my.test;
    
    public class MyTestClass {
    
        public static void main(String [] args)
        {
    
            MyInterface myInterface = new MyInterface() {
    
                @Override
                public void go() {
                    System.out.println("Go ...");
    
                }
    
                @Override
                public void doSome() {
                    System.out.println("Do ...");
    
                }
            };
    
            myInterface.doSome();
            myInterface.go();
        }
    
    }
    

提交回复
热议问题