简体   繁体   English

调用抽象类的构造函数

[英]Calling the constructor of an abstract class

Say I have the following class structure: 假设我有以下类结构:

public class A{
    A(int a){
        ...
    }
}

abstract class B extends A{

}

public class C extends B{
    C(int a){
        super(a);
    }
}

This code isn't valid in the sense that myMethod will not call A's constructor. 在myMethod不会调用A的构造函数的意义上,此代码无效。 Is there a way to do this? 有没有办法做到这一点?

What I ultimately want to do, is add functionality to a set of classes without affecting their functionality. 我最终想要做的是在不影响其功能的情况下为一组类添加功能。 All these classes currently extend a common class (runtimeException), so I was thinking of adding an intermediary abstract class. 所有这些类当前都扩展了一个公共类(runtimeException),所以我想添加一个中间抽象类。

(edit: the code in C shouldn't be a method, it was meant to be a constructor) (编辑:C中的代码不应该是一个方法,它应该是一个构造函数)

You will not be able to declare class B like you wrote. 你不能像你写的那样申报B级。 To create an instance of B you'll need to call A constructor: 要创建B的实例,您需要调用A构造函数:

public abstract class B extends A {
    public B() {
        super(10); //or other number
    }
}

public class C extends B {
    public C(int a) {
        super();
    }
}

In other words, you always call constructor of "previous level", whether the class is abstract or not. 换句话说,你总是调用“上一级”的构造函数,无论类是否是抽象的。

In order to avoid this strange number 10 I wrote and missing int parameter of C constructor, I suggest adding to child class constructor at least all parameters parent class constructor requires for any extends pair of classes. 为了避免这个奇怪的数字10我编写并缺少C构造函数的int参数,我建议至少为子类构造函数添加父类构造函数对任何extends对类所需的所有参数。

What I've seen commonly is a pattern like this: 我经常看到的是这样的模式:

public class A{
    A(int a){
        ...
    }
}

abstract class B extends A{
    B(int a) {// "proxy" constructor"
        super(a);
    }
}

public class C extends B{
    C(int a) {
         super(a);
    }

    void myMethod(int a){
        // super(a); <- note this is invalid code, you can only call this from the constructor
        new C(0); // <-- this is valid
    }
}

Granted, it's a bit verbose and boilerplate-y, but it allows you to avoid duplicating any functionality 当然,它有点冗长和样板,但它允许您避免重复任何功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM