java - 如何在不编写重复代码的情况下处理继承链中的默认值?

标签 java inheritance

假设我有类 A,其定义如下:

 public class A{
    private int x;

    public A(){
        this(13);
    }
    public A(int x){
        this.x = x;
    }
}

然后我有一个类 B 需要实现 y,所以像这样:

public class B extends A{
    private int y;

    public B(){

    }
    public B(int x){
        this(x, 0);
    }
    public B(int x, int y){
        super(x);
        this.y = y;
    }
}

我的问题是:我在public B() 中做什么?我是调用 super() 以便 A 分配默认值/做任何事情,然后在该构造函数中执行另一个 this.y = y,还是调用 this(13)?

这两种方法似乎都需要一些不好的做法。一个让我在两个地方写 this.y = y。另一个要求我重复默认值,并且每次更改默认值时都需要更改。

最佳答案

如果字段不是最终的,您可以在声明它们的地方分配默认值。所以代码看起来像:

class A{
  private int x = 13;
  public A(){
    //use default value for x
  }
  public A(int x){
    this.x = x;
  }
}

class B extends A {
  private int y = 0;
  public B(){ 
    //use default value for x and y
  }
  public B(int x){
    super(x);
    //use default value for y
  }
  public B(int x, int y){
    super(x);
    this.y = y;
  }
}

关于java - 如何在不编写重复代码的情况下处理继承链中的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38247062/

相关文章:

inheritance - 如何在 Laravel 的 Eloquent 中对 Table-Per-Type 继承进行建模?

swift - 从 NSObject 继承的对象导致错误 Property 'self._username' not initialized at super.init call

java - 从父类对象调用子类方法

java - 使用 Apache Flink 从 Web 获取 JSON 元素

java - 构建时 Maven MOJO 执行失败

java - SBT 在尝试运行简单的 "Hello!"示例脚本时给出 java.lang.NullPointerException

java - 如何获取以前的网址?

Java 8 : Executing reduce operation on Stream

java - Java中的implements和extends关键字有什么区别

sql - Hibernate 的继承