Can an abstract class have a constructor?

前端 未结 22 2177
甜味超标
甜味超标 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:22

    Not only can it, it always does. If you do not specify one then it has a default no arg constructor, just like any other class. In fact, ALL classes, including nested and anonymous classes, will get a default constructor if one is not specified (in the case of anonymous classes it is impossible to specify one, so you will always get the default constructor).

    A good example of an abstract class having a constructor is the Calendar class. You get a Calendar object by calling Calendar.getInstance(), but it also has constructors which are protected. The reason its constructors are protected is so that only its subclasses can call them (or classes in the same package, but since it's abstract, that doesn't apply). GregorianCalendar is an example of a class that extends Calendar.

    0 讨论(0)
  • 2020-11-22 06:23

    Abstract class can have a constructor though it cannot be instantiated. But the constructor defined in an abstract class can be used for instantiation of concrete class of this abstract class. Check JLS:

    It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation expression.

    A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class.

    0 讨论(0)
  • 2020-11-22 06:26

    Yes it can have a constructor and it is defined and behaves just like any other class's constructor. Except that abstract classes can't be directly instantiated, only extended, so the use is therefore always from a subclass's constructor.

    0 讨论(0)
  • 2020-11-22 06:27

    Consider this:

    abstract class Product { 
        int value;
        public Product( int val ) {
            value= val;
        }
        abstract public int multiply();
    }
    
    class TimesTwo extends Product {
        public int mutiply() {
           return value * 2;
        }
    }
    

    The superclass is abstract and has a constructor.

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