Can an abstract class have a constructor?

前端 未结 22 2497
甜味超标
甜味超标 2020-11-22 05:25

Can an abstract class have a constructor?

If so, how can it be used and for what purposes?

22条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 06:21

    Yes, an abstract class can have a constructor. Consider this:

    abstract class Product { 
        int multiplyBy;
        public Product( int multiplyBy ) {
            this.multiplyBy = multiplyBy;
        }
    
        public int mutiply(int val) {
           return multiplyBy * val;
        }
    }
    
    class TimesTwo extends Product {
        public TimesTwo() {
            super(2);
        }
    }
    
    class TimesWhat extends Product {
        public TimesWhat(int what) {
            super(what);
        }
    }
    

    The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.

    Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.

    NOTE: As there is no default (or no-arg) constructor in the parent abstract class, the constructor used in subclass must explicitly call the parent constructor.

提交回复
热议问题