2014-04-29 2 views
-2

선생님이 채워 주신 코드에 문제가 있습니다.정적 클래스 팩터 리 메서드에서 속성 가져 오기

저는 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 
    } 
} 

임은이 모든 정보가 들어있는 파일을 읽을 예정.

내게 큰 의문은 어떻게 그런 정적 팩터드 메소드가있는 경우 그 함수를 사용할 수 있습니까? 해당 정보를 얻으려고 애쓰는 데 어려움을 겪고 있습니다.

나는 예를 들어도 일부 JTestUnits을 받았다 :

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

답변

0

당신은 당신의 추상 클래스에 두 개의 속성 (라이센스 및 색상)을 추가해야합니다. 하위 클래스에는 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; 
    } 
} 
+0

고맙습니다. :) 문제가 해결되어서 문제가 해결되었습니다. – JDev

+0

당신을 환영합니다 ^^ – TheNawaKer

관련 문제