我想知道如果我以这种方式定义,为什么只能在构造函数中设置数据:
public Auto(int ps, String kennzeichen) {
super(ps,kennzeichen);
this.ps = ps;
this.kennzeichen = kennzeichen;
}
如果我离开 this.ps 和 this.kennzeichen,它将用 null 初始化。我认为"super"定义为从我的Vehikel类构造函数继承数据。
主要:
public class Main {
public static void main(String[] args) {
ArrayList vehikel = new ArrayList();
Scanner scinner = new Scanner(System.in);
boolean eingabeFortf = true;
Auto auto = new Auto(12, "HE-ML 123");
System.out.println(auto.getKW());
System.out.println(auto.getKennzeichen());
System.out.println(auto.getPS());
维希克尔:
public abstract class Vehikel {
private int ps;
private String kennzeichen;
public final double uFaktor = 0.735;
public Vehikel(int ps, String kennzeichen) {
this.ps = ps;
this.kennzeichen = kennzeichen;
}
自动:
public class Auto extends Vehikel {
private String kennzeichen;
private int ps;
private double kW;
private boolean mayDriveOnH;
private double steuer = 0;
public Auto(int ps, String kennzeichen) {
super(ps,kennzeichen);
this.ps = ps;
this.kennzeichen = kennzeichen;
}
谢谢。
我不熟悉Java,但这样的事情应该走上正轨。希望一些Java人员能够纠正下面的任何错误。
守则:
public abstract class Vehikel {
protected int ps; // change to protected
protected String kennzeichen; // change to protected
public final double uFaktor = 0.735;
public Vehikel(int ps, String kennzeichen) {
this.ps = ps;
this.kennzeichen = kennzeichen;
}
public class Auto extends Vehikel {
// private String kennzeichen; // we have the protected field in the super class
// private int ps; // we have the protected field in the super class
private double kW;
private boolean mayDriveOnH;
private double steuer = 0;
public Auto(int ps, String kennzeichen) {
super(ps,kennzeichen);
// this.ps = ps; // You don't need this anymore because you can access the protected variable in the super class directly
// this.kennzeichen = kennzeichen; // You don't need this anymore because you can access the protected variable in the super class directly
}
解释:
正如Andy Turner上面所说,当你在抽象类和具体Auto
类中具有相同的变量时,一个中的变量hide
超/抽象类中的变量。
基本上,它们是具有相同名称的不同变量
我不能说得比这更好。
使用 protected 关键字,以便您可以在Auto
auto 类中访问超类中定义的变量。