Can an abstract class have a constructor?

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

    The purpose of the constructor in a class is used to initialize fields but not to "build objects". When you try to create a new instance of an abstract SuperClass, the compiler will give you an error. However, we can inherit an abstract class Employee and make use of its constructor by setting its variables See example below

    public abstract class Employee {
      private String EmpName;
      abstract double calcSalary();
    
      Employee(String name) {
        this.EmpName = name;// constructor of abstract class super class
      }
    }
    
    class Manager extends Employee{
     Manager(String name) {
        super(name);// setting the name in the constructor of sub class
     }
    double calcSalary() {
        return 0;
     }
    }
    

提交回复
热议问题