开始学习 Java,但无法弄清楚继承是如何工作的。
有一个类继承自 Pane。
public class Tone extends Pane{
int x = 100;
int y = 100;
Background skin = new Background(new BackgroundFill(Color.rgb(255, 255, 0), CornerRadii.EMPTY, Insets.EMPTY));
Tone() {
this.setPrefSize(this.x, this.y);
this.setBackground(this.skin);
this.setOnMouseEntered(e ->{
show();
});
this.setOnMouseExited(e -> {
show();
});
}
void show() {
if(this.getChildren().isEmpty()) {
Text stat = new Text(this.x + " " + this.y);
this.getChildren().add(stat);
}
else {
this.getChildren().clear();
}
}
}
另一个类继承自这个类,其中变量的值发生了变化。
public class Ttwo extends Tone {
int x = 300;
Background skin = new Background(new BackgroundFill(Color.rgb(255, 0, 0), CornerRadii.EMPTY, Insets.EMPTY));
}
创建对象时,Ttwo 不会更改其大小、显示值或背景颜色。
告诉我,错误是什么?
类中没有一个地方
Ttwo
可以使用变量x
,skin
而且,用父类的名称命名子类的变量是一种风格错误。通过在实例上调用 show() 方法
Ttwo
,执行写入的代码块Tone
并使用位于同一文件中的变量。您需要的是在构造函数Ttwo
中将变量的值传递给父类。