What is the use of creating a constructor for an abstract class in Java?

前端 未结 8 2066
时光取名叫无心
时光取名叫无心 2020-12-03 18:50

I would like to know what purpose a constructor for an abstract class serves; as we do not instantiate abstract classes, why would we ever need such a constructor?

8条回答
  •  温柔的废话
    2020-12-03 19:25

    You don't instantiate abstract classes but the constructor is invoked when a subclass is instantiated.

    The use could be to initialize common attributes ie.

    import java.util.List;
    import java.util.ArrayList;
    abstract class BaseClass {
        protected List list; // visible from subclasses
    
        public BaseClass() {
            System.out.println("to abstract...");
            // common initialization to all subclasses
            list = new ArrayList();
            list.add("a");
            list.add("a");
            list.add("a");
        }
    }
    
    class ConcreteClass extends BaseClass {
        public ConcreteClass(){
            // The list is initialized already
            System.out.println("now it is concrete and the list is: = "+ this.list );
    
    
        }
    }
    
    class TestAbstractClass {
        public static void main( String [] args ) {
            BaseClass instance = new ConcreteClass();
        }
    
    }
    

    Output

    $ java TestAbstractClass
    to abstract...
    now it is concrete and the list is: = [a, a, a]
    

提交回复
热议问题