我被Java OOP问题困住了。我想出了一些玩具代码来解释这个问题。这是我的课-
第 1 类 - Car.java
public class Car {
public void reportProblem(String problem){
ReportUtil.reportVehicleInfo("Car", 4, problem); //4 is number of wheels
}
//bunch of other methods
}
第 2 类 - Truck.java
public class Truck {
public void reportProblem(String problem){
ReportUtil.reportVehicleInfo("Truck", 6, problem);
}
//bunch of other methods
}
第 3 类 - ReportUtil.java
public class ReportUtil {
public static void reportVehicleInfo(String name, int wheels, String problem){
System.out.println(String.format("%s %s %s", name, wheels, problem));
}
}
第 4 类 - Test.java
public class Test {
public static void main(String[] args) {
Car c = new Car();
c.reportProblem("puncture");
Truck t = new Truck();
t.reportProblem("engine missing");
}
}
我想将“Car”和“Truck”中的“reportProblem”方法实现抽象到父类。这就是我所做的 -
第 1 类 - Vehicle.java
public abstract class Vehicle {
public String mName;
public int mNumWheels;
public void reportProblem(String problem){
ReportUtil.reportVehicleInfo(mName, mNumWheels, problem);
}
public void setName(String name){
mName = name;
}
public void setNumWheels(int numWheels){
mNumWheels=numWheels;
}
}
第 2 类 - Car.java
public class Car extends Vehicle {
//bunch of other methods
}
第 3 类 - Truck.java
public class Truck extends Vehicle {
//bunch of other methods
}
第 4 类 - ReportUtil.java(未对此类进行更改)。
public class ReportUtil {
public static void reportVehicleInfo(String name, int wheels, String problem){
System.out.println(String.format("%s %s %s", name, wheels, problem));
}
}
第 5 类 - Test.java
public class Test {
public static void main(String[] args) {
Car c = new Car();
c.setName("Car"); //NOTE : Can be missed!
c.setNumWheels(4); //NOTE : Can be missed!
c.reportProblem("puncture");
Truck t = new Truck();
t.setName("Truck"); //NOTE : Can be missed!
t.setNumWheels(6); //NOTE : Can be missed!
t.reportProblem("engine missing");
}
}
这达到了我想要的(我已经抽象了“reportProblem”的实现)。但我知道这不是最好的方法。一个原因是不应该调用“reportProblem”方法而不调用“setName”和“setNumWheels”方法。否则将传递“null”。有没有一种方法可以在调用 reportProblem 之前使用一些 OOP 技术来执行两种方法调用(setName 和 setNumWheels)?
我希望我已经说清楚了。如果我不是,请告诉我你会怎么做,这样我就可以从中学习。