首先,我认为这篇文章的标题可以更好,所以如果你想编辑它,请随意这样做(或者告诉我你认为我应该如何编辑它)。
我正在复习Java面试的练习题。我现在没有参加面试,但我认为这是发现我在Java方面所有弱点的最好方法。在你说之前,是的,我发现我在Java的很多方面都很弱,我需要在面试前做很多复习。
我对以下代码有一些疑问:
public class VehicleApp {
public static void main(String[] args) {
Ford myFord = new Ford();
System.out.println(myFord.countWheels());
Kawasaki myKawasaki = new Kawasaki(1985, "Eliminator");
System.out.println(myKawasaki.countWheels());
}
}
class Vehicle {
protected String make;
protected int numWheels;
public Vehicle() { }
public String countWheels() {
return "The number of wheels this " + make + " has is " + numWheels + ".";
}
}
class Ford extends Vehicle {
public Ford() {
make = "Ford";
numWheels = 4;
}
}
class Kawasaki extends Vehicle {
private String model;
private int year;
public Kawasaki(int year, String model) {
make = "Kawasaki";
numWheels = 2;
this.model = model;
this.year = year;
}
public String countWheels() {
return "The number of wheels this " + year + " " + make + " " + model + " has is " + numWheels + ".";
}
}
首先,我注意到代码中没有对super()的引用。我认为,当您处理超类和子类时,需要子类构造函数以super()的形式包含对超类构造函数的引用;(如果超类构造函数有参数,也包括参数)。然而,这段代码似乎没有它们也能工作。这个要求我错了吗?我还遗漏了什么吗?
第二,Kawasaki类没有为countWheels()方法包含@Override装饰。因为这个方法有相同的名称(尽管不同的参数)作为超类的countWheels()方法,难道不需要有一个@Override装饰吗?或者只有当参数是相同的类型和相同的顺序?
谢谢!
如果您没有在派生类中显式调用super()
, Java编译器将自动为您生成对super()
的调用。当然,这只在基类构造函数不带参数的情况下才有效。这可以通过在Vehicle
构造函数中添加System.out.println("Constructor called.");
语句来演示。
@Override
装饰器,正如你已经发现的,但还没有说服自己,是可选的。但它被认为是"最佳实践"。如果更改方法签名,则在重写方法以捕获错误时使用此方法。
Vehicle
必须具有make和numWheels属性,因此我个人要求在Vehicle
构造函数中指定这些属性。现在不可能有一个未定义这些属性的派生类。
public class VehicleApp {
public static void main(String[] args) {
Ford myFord = new Ford();
System.out.println(myFord.countWheels());
Kawasaki myKawasaki = new Kawasaki(1985, "Eliminator");
System.out.println(myKawasaki.countWheels());
}
}
class Vehicle {
protected String make;
protected int numWheels;
public Vehicle(String make, int numWheels) {
this.make = make;
this.numWheels = numWheels;
}
public String countWheels() {
return "The number of wheels this " + make + " has is " + numWheels + ".";
}
}
class Ford extends Vehicle {
public Ford() {
super("Ford", 4);
}
}
class Kawasaki extends Vehicle {
private String model;
private int year;
public Kawasaki(int year, String model) {
super("Kawasaki", 2);
this.model = model;
this.year = year;
}
@Override
public String countWheels() {
return "The number of wheels this " + year + " " + make + " " + model + " has is " + numWheels + ".";
}
}