2014-03-02 4 views
-1

부모 클래스가 Product이고 자식이 Food입니다. 모든 Product에는 배달 시간이 있습니다. 예를 들어 Food의 경우 1 일입니다 (하나의 int으로 정의 됨). 정적 값을 사용한 상속

는이 같은 내 Product 클래스를 만든 :

public abstract class Product {  
    private int id; 
    private String description; 
    private double price; 

    public Product(int id, String description, double price) { 
     this.id = id; 
     this.description = description; 
     this.price = price; 
    }.... and so on 

Food 클래스는 다음과 같습니다

public class Food extends Product{ 

    private Date expirationDate; 
    private static final int DELIVERY = 1; 

    public Food(int id, String description, double price, Date expirationDate) { 
     super(id, description, price); 
     this.expirationDate = expirationDate; 
    }.. and so on 

이이 일을 적절한 방법이 있나요? 둘째, 내 변수 DELIVERYFood에서 어떻게 호출 할 수 있습니까?

희망 사항 저는 제 질문에 분명합니다.

+1

"이 작업을 수행하는 적절한 방법입니까?" - 뭐라구? 계승? 훌륭해. "어떻게 변수를 '식품'에서 '전달'이라고 부를 수 있습니까? 그냥 사용하십시오. 정의되어 있으므로 아무런 문제가 없습니다. – AlexR

+0

@AlexR : 부모로부터 자식 필드에 어떻게 액세스 할 수 있습니까? – mok

+0

전달을 위해 부모 클래스에서 변수를 다른 방법으로 지정해야합니까? – ddvink

답변

0

모든 제품에 배달 시간이있는 경우 기본 클래스를 넣는 것이 좋습니다.

public abstract class Product { 

private int id; 
private String description; 
private double price; 

protected final int deliveryTime; 

public Product(int id, String description, double price, int deliveryTime) { 
    this.id = id; 
    this.description = description; 
    this.price = price; 
    this.deliveryTime = deliveryTime; 
} 

public class Food extends Product{ 
public Food(int id, String description, double price, Date expirationDate) { 
    super(id, description, price, 1); 
    this.expirationDate = expirationDate; 
} 
//... 
} 

내가 배달 어머니 클래스에 보호를 만들었지 만, 당신은뿐만 아니라 그것을 비공개로하고 해당 분야가 서로 액세스 할 경우에만 (세터/게터가있을 수 있습니다

그래도 코드의 일부).

1

모든 제품은 deliverytime

난 당신이 어떤 제품을 위해, 외부에서이 정보에 액세스 할 수 있도록하려는 생각을 가지고있다. 따라서 Product 클래스에는 다음과 같은 메서드가 있어야합니다.

/** 
* Returns the delivery time for this product, in days 
*/ 
public int getDeliveryTime() 

이제는 궁금해 할 점이 있습니다. 배달 시간은 모든 제품에 대한 고정 값이며, 건설 시간에 계산 될 수 있으며 나중에 변경되지 않거나 제품의 다른 필드에서 계산 된 배달 시간이거나 수식에 따릅니다. , 각 서브 클래스를 계산하도록해야 (귀하의 경우 것 같다) 두 번째 경우

private int deliveryTime; 

protected Product(int id, String description, double price, int deliveryTime) { 
    this.id = id; 
    this.description = description; 
    this.price = price; 
    this.deliveryTime = deliveryTime; 
} 

/** 
* Returns the delivery time for this product, in days 
*/ 
public int getDeliveryTime() { 
    return deliveryTime; 
} 

: 첫 번째 경우에, 배달 시간은 생성자에서 초기화 Product 클래스의 필드가 될 수 있습니다 배달 시간은 원하는대로에 :

/** 
* Returns the delivery time for this product, in days 
*/ 
public abstract int getDeliveryTime(); 

식품, 예를 들어

:

@Override 
public int getDeliveryTime() { 
    return 1; // always 1 for Food. Simplest formula ever 
} 

좋은 점은 제품 클래스의 사용자와 서브 클래스이게 얼마나 신경 쓸 필요가 없다는 것입니다 구현하다 mented. 각각의 Product에는 getDeliveryTime() 메서드가 있습니다. 구현 방법은 관련이 없으며 호출자 코드에서 아무 것도 변경하지 않고 변경할 수 있습니다. 그것은 캡슐화의 아름다움입니다.