抽象类可以有构造函数吗?
如果可以,如何使用它,用于什么目的?
抽象类可以有构造函数吗?
如果可以,如何使用它,用于什么目的?
当前回答
是的,当然你可以添加一个,就像前面提到的抽象类变量的初始化一样。 但是如果你没有显式地声明一个,它无论如何都有一个隐式的构造函数来“构造函数链接”工作。
其他回答
package Test1;
public class AbstractClassConstructor {
public AbstractClassConstructor() {
}
public static void main(String args[]) {
Demo obj = new Test("Test of code has started");
obj.test1();
}
}
abstract class Demo{
protected final String demoValue;
public Demo(String testName){
this.demoValue = testName;
}
public abstract boolean test1();
}
class Test extends Demo{
public Test(String name){
super(name);
}
@Override
public boolean test1() {
System.out.println( this.demoValue + " Demo test started");
return true;
}
}
为了实现构造函数链接,抽象类将有一个构造函数。 编译器将Super()语句保存在子类构造函数中,该语句将调用父类构造函数。如果抽象类没有构造函数,那么就违反了java规则,我们就无法实现构造函数链接。
是的,抽象类可以有构造函数。考虑一下:
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);
}
}
父类Product是抽象的,并且有一个构造函数。具体类TimesTwo有一个只硬编码值2的构造函数。具体类TimesWhat有一个构造函数,允许调用者指定值。
抽象构造函数将经常用于强制类约束或不变量,例如设置类所需的最小字段。
注意:因为在父类中没有默认(或无参数)构造函数 抽象类,在子类中使用的构造函数必须显式调用 父构造函数。
是的。当创建继承类的实例时,调用抽象类的构造函数。例如,下面是一个有效的Java程序。
// An abstract class with constructor
abstract class Base {
Base() { System.out.println("Base Constructor Called"); }
abstract void fun();
}
class Derived extends Base {
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {
Derived d = new Derived();
}
}
这是上面代码的输出,
基本构造函数Called 派生构造函数调用
引用: 在这里输入链接描述
类中构造函数的作用是初始化字段,而不是“构建对象”。当您尝试创建一个抽象SuperClass的新实例时,编译器会给您一个错误。然而,我们可以继承一个抽象类Employee,并通过设置其变量来使用其构造函数(参见下面的示例)
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;
}
}