从静态类工厂方法获取一个属性



老师让我填写的一些代码有问题。

我有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()) {
    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函数?我在获取这些信息时遇到了困难,我很乐意提供一些提示。

我也得到了一些JTestUnits,例如:

   Car c = new LightCar(3, "Volvo");
        assertEquals(c.getColor(), "Red");

您必须向抽象类添加两个属性(Licence和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;
    }
}

最新更新