2012-09-28 4 views
2

좋아요, 그래서 저는 MonthlyReports라는 클래스의 고객에 관한 파일에서 많은 정보를 읽었습니다. 또한 Customer라는 클래스가 있고 getTotalFees라는 메서드를 재정의하려는 경우 getTotalFees를 재정의하려는 StandardCustomer 및 PreferredCustomer라는 두 개의 하위 클래스가 있습니다. 읽혀지는 중요한 정보 중 하나는 고객이 선호하는지 아니면 표준인지 (변수 플래그에 저장되어 있는지 여부입니다. 그러나 내 문제는 고객이 표준인지 여부를 결정하는 위치/방법을 모르는 것입니다.) 또는 선호했다.Java의 메소드를 조건부로 오버라이드

여기, Customer 클래스에 내 생각을 한 추상적 인 방법 getTotalFees

내 표준 및 기본 클래스에서 다음
public double abstract getTotalFees() { 
    return this.totalFees; 
} 

나는 무시 방법이 그것

public double getTotalFees() { 
    if (flag.equals("S"){ 
     return this.totalFees * 5; 
    } else { 
     return this.totalFees; 
    } 
} 

나는 단지 이해하고있다. 여기 빨대에서 보내므로 어떤 도움을 주시면 감사하겠습니다.

답변

1

팩토리 메서드 (일명 "가상 생성자")가 필요합니다. 다형성으로 인해이 문제가 해결됩니다. 이것은 객체 지향 프로그래밍의 특징 중 하나입니다.

public class StandardCustomer extends Customer { 
    // There's more - you fill in the blanks 
    public double getTotalFees() { return 5.0*this.totalFees; } 
} 

public class PreferredCustomer extends Customer { 
    // There's more - you fill in the blanks 
    public double getTotalFees() { return this.totalFees; } 
} 

public class CustomerFactory { 
    public Customer create(String type) { 
     if ("preferred".equals(type.toLowerCase()) { 
      return new PreferredCustomer(); 
     } else { 
      return new StandardCustomer(); 
     } 
    } 
} 
+0

감사합니다. 이것은 내가 묻는 것보다 더 많습니다. –

4

당신은 이미 당신이 방법의 두 가지 버전이 있습니다 PreferredCustomer 두 개의 서로 다른 클래스 StandardCustomer을 가지고있는 경우 :

자바

동적 파견이의 실행시의 형태에 따라 적절한 방법이 관련되어 있음을 걱정한다

//in StandardCustomer: 
@Override 
public double getTotalFees() { 
    return this.totalFees * 5; 
} 

//in PreferredCustomer: 
@Override 
public double getTotalFees() { 
    return this.totalFees; 
} 
예.