Can an abstract class have a constructor?

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

    Although there are many good answers, I would like to give my 2 cents.

    Constructor DOES NOT BUILD THE OBJECT. It is used to initialize an object.

    Yes, an Abstract class always has a constructor. If you do not define your own constructor, the compiler will give a default constructor to the Abstract class. Above holds true for all classes - nested, abstract, anonymous, etc.

    An abstract class (unlike interface) can have non-final non-static fields which need initialization. You can write your own constructor in the abstract class to do that. But, in that case, there won't be any default constructor.

    public abstract class Abs{
        int i;
        int j;
        public Abs(int i,int j){
            this.i = i;
            this.j = j;
            System.out.println(i+" "+j);
        }
    }
    

    Be careful while extending above abstract class, you have to explicitly call super from each constructor. The first line of any constructor calls to super(). if you do not explicitly call super(), Java will do that for you. Below code will not compile:

    public class Imp extends Abs{
    
    public Imp(int i, int j,int k, int l){
        System.out.println("2 arg");
    }
    }
    

    You have to use it like below example:

    public class Imp extends Abs{
    
    public Imp(int i, int j,int k, int l){
        super(i,j);
        System.out.println("2 arg");
    }
    }
    

提交回复
热议问题