Java 从静态类工厂方法获取属性
我在老师给我的一些代码上遇到了一些问题 我有一个类Car,然后是另外两个子类,LightCar和heavyCar,它们将扩展Car类。 基本上我得到的是这样的东西:Java 从静态类工厂方法获取属性,java,function,static,attributes,abstract,Java,Function,Static,Attributes,Abstract,我在老师给我的一些代码上遇到了一些问题 我有一个类Car,然后是另外两个子类,LightCar和heavyCar,它们将扩展Car类。 基本上我得到的是这样的东西: public abstract class Car{ public static Car newCar(File file) throws FileNotFoundException { carType = null; Scanner in = new Scanner(file); while (in.hasNext()) {
public abstract class Car{
public static Car newCar(File file) throws FileNotFoundException {
carType = null;
Scanner in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
String tokens[] = line.split(";");
if (line.contains("Light Weight")) {
LightCar lightC = new LightCar(Long
.valueOf(tokens[1]).longValue(), tokens[3]);
in.close();
carType = lightC;
}
if (line.contains("Heavy Weight")) {
HeavyCar heavyC = new HeavyCar(Long.valueOf(
tokens[1]).longValue(), tokens[3]);
in.close();
carType = heavyC;
}
}
in.close();
return carType;
}
public getLicense(){
return.. // PROBLEM HERE
}
}
public getCarColor(){
return.. PROBLEM HERE
}
}
我应该读一个包含所有这些信息的文件
我的大问题是,如果我有一个静态工厂方法,我如何使用这些get函数?
我在获取这些信息时遇到了困难,希望能得到一些提示
我也得到了一些测试单元,例如:
Car c = new LightCar(3, "Volvo");
assertEquals(c.getColor(), "Red");
必须向抽象类添加两个属性license和Color。 您的子类现在有两个新属性以及getter和关联setter
public abstract class Car{
private String licence;
private String color;
public static Car newCar(File file) throws FileNotFoundException {
carType = null;
Scanner in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
String tokens[] = line.split(";");
if (line.contains("Light Weight")) {
LightCar lightC = new LightCar(Long
.valueOf(tokens[1]).longValue(), tokens[3]);
//Read here the color and the licence
lightC.setColor(...);
lightC.setLicence(...);
//replace "..." by your value
in.close();
carType = lightC;
}
if (line.contains("Heavy Weight")) {
HeavyCar heavyC = new HeavyCar(Long.valueOf(
tokens[1]).longValue(), tokens[3]);
//same as above
in.close();
carType = heavyC;
}
}
in.close();
return carType;
}
public String getLicense(){
return licence;
}
public void setLicence(String licence){
this.licence=licence;
}
public String getCarColor(){
return color;
}
public void setColor(String color){
this.color=color;
}
}
谢谢:这就把事情弄清楚了,我想这也解决了我的问题!