简体   繁体   English

在抽象类中声明具体方法

[英]Declaring concrete method in abstract class

I need to override toString() method for all of the concrete method of my abstract class - exactly the same in all cases.我需要为我的抽象类的所有具体方法覆盖toString()方法 - 在所有情况下都完全相同。 So here is what I want to do ( SomeEnum is a separate class which has just an enum declaration):所以这就是我想要做的( SomeEnum是一个单独的类,它只有一个枚举声明):

abstract class抽象类

public abstract class ClassA {
    protected SomeEnum name;
    protected int some_int;

// Constructor here

@Override
public String toString() {
    return name.toString().toLowerCase() + " > " + Integer.toString(some_int);
}
}

concrete class (example)具体类(示例)

public class ClassB extends ClassA {
    private static final int some_const = 1;
    private SomeEnum name = SomeEnum.ENUM_1;

public ClassB(int some_int) {
    super(some_const, some_int);
}
}

For some reason I cannot do it that way without runtime exceptions and I need to declare abstract method in the abstract class and then provide (exactly the same) implementation of toString() in every of the concrete classes implementations.出于某种原因,我不能在没有运行时异常的情况下这样做,我需要在抽象类中声明抽象方法,然后在每个具体类实现中提供(完全相同) toString()实现。

What is wrong with this approach?这种方法有什么问题?

EDIT: The exception I get is NullPointerException that then points me to ClassA.toString() .编辑:我得到的异常是NullPointerException然后将我指向ClassA.toString()

Instead of declaring name as a field on ClassB assign someEnum in the constructor of ClassB so it uses the field from the supertype.相反的声明name作为一个字段ClassB分配someEnum在构造函数ClassB所以它使用领域从超类型。 The supertype does not have access to the name field on the subtype, which causes the NPE when toString is called.超类型无法访问子类型上的name字段,这会在调用toString时导致 NPE。

public ClassB(int some_int) {
    super(some_const, some_int);
    this.name = SomeEnum.ENUM_1;
}

Full Example完整示例

ClassB B级

public class ClassB extends ClassA {
    private static final int some_const = 1;

    public ClassB(int some_int) {
        super(some_const, some_int);
        this.name = SomeEnum.ENUM_1;
    }

    public static void main(String[] args) {
        ClassB b = new ClassB(4);
        b.toString();
    }
}

ClassA A类

public abstract class ClassA {
    protected SomeEnum name;
    protected int some_int;

    public ClassA(int someConst, int some_int2) {
    }

    @Override
    public String toString() {
        return name.toString().toLowerCase() + " > "
                + Integer.toString(some_int);
    }

}

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

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