2013-01-31 2 views
3

저는 Java 연습 과제를 진행하고 있으며 내가 잘못하고있는 것을 파악할 수 없습니다. 나는 Movie 클래스 (변수 : rating, title, movieId 및 FEE_AMT에 대한 상수)를 만든 다음 Action, Comedy 및 Drama로 클래스를 확장했습니다. 이러한 파생 클래스에는 다른 변수가 없으며 다른 FEE_AMT 만 있습니다. 난 그냥 예를 들어, 객체와 크게 메소드를 호출하면자바 재정의 메소드가 호출되지 않습니다.

/** 
* Returns the late fee due on a Movie rental 
* @param days the number of days for late fee calculations 
* @return true or false depending on the evaluation of the expression 
**/ 
public double calcLateFees(int days){ 
    return(days * FEE_AMT); 
} 

:

는 영화 (및 파생 클래스)에 의한 연체료를 계산하는 방법이있다 comedy1.calcLateFees(2) -이 생성됩니다 올바른 수수료 금액은 파생 된 방법의 다른 상수 값을 기반으로합니다.

이제는 Rental 클래스를 만들고 main()에 렌탈 객체 (renterId 및 daysLate로 구성됨)를 보유 할 렌탈 유형의 배열을 생성해야했습니다. 여기에 대여 객체의 배열에 취해 배열의 모든 대여에 의한 연체료 반환하는 방법입니다 :

/** 
* lateFeesOwed returns the amount of money due for late fees on all movies 
* which are located in an array of Rentals. 
* 
* @return feeDue the amount of money due for late fees. 
*/ 
public static double lateFeesOwed(Rental[] rentalArray){ 
    double feeDue = 0; 

    for(int i = 0; i < rentalArray.length; i++) 
    { 
     feeDue += rentalArray[i].calcFees(); //This is part of the problem?? 

    } 

    return feeDue; 
} 

및이 방법은 호출

/** 
* CalcFees returns the amount of money due for late fees on a movie rental. 
* 
* @return feeDue the amount of money due for late fees. 
*/ 
public double calcFees(){ 
    double feeDue = rentalName.calcLateFees(this.daysLate); 
    return feeDue; 
} 

그러나 문제는이다 calcFees() 메서드는 calcLateFees()을 호출하지만 파생 클래스를 호출하는 대신 Movie 클래스를 호출하고 잘못된 값을 반환합니다.

오버라이드 된 메서드 calcLateFees()이 내 문제로 인해 호출되지 않도록 확실하지 않습니다.

감사합니다.

답변

6

이러한 파생 클래스에는 다른 변수가 없으며 다른 FEE_AMT 만 있습니다.

이것은 문제입니다. 데이터 멤버는 다형성이 아닙니다. 필요한 것은 FEE_AMT을 메서드로 바꾸고 파생 클래스에서이 메서드를 재정의하는 것입니다.

// Movie 

public double calcLateFees(int days){ 
    return(days * getFeeAmt()); 
} 

protected abstract double getFeeAmt(); // or implement if you wish 

// Action etc 

@Override 
protected double getFeeAmt() { return ...; } 
+2

너무 빠르다 !! – Scorpion

+0

+1, 나는 두 번 전부를 읽을 필요가 있었고, 나는 이미 여기에 답이 있음을 알기 전에 .. : P – PermGenError

관련 문제