2014-03-02 77 views
-1

我有一个父类称为Product和一个孩子叫Food。每个Product都有一个交货时间。例如对于Food这是一天(我定义为一个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 

这是这样做的正确方法?第二,如何从Food拨打我的变量DELIVERY

希望我在我的问题中很清楚。

+1

“这是做这件事的正确方法吗?” - 做什么?遗产?你做到了。 “我怎样才能从食物中调用我的变量'DELIVERY'” - 只是使用它。它是在那里定义的,所以没有问题来提及它。 – 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; 
} 
//... 
} 

我的交付55保护在母亲类,但你不妨把它变成私有,并有一个setter /吸气(仅当您希望该字段为能够与其他访问部分代码尽管)。

1

每个产品都有一个交货期

我猜你希望能够从外部访问这些信息,对于任何产品。所以你的产品类必须有如下方法:

/** 
* 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; 
} 

在第二种情况下,(这似乎是你的情况下),你应该让每个子类计算交货时间,因为它想:

/** 
* 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 
} 

很酷的事情是,该产品类的用户和子类并不需要关心这是怎么回事imple mented。他们只知道每个Product都有一个getDeliveryTime()方法。它的实现方式与它们无关,并且可以在不更改调用者代码中的任何内容的情况下进行更改。这就是封装的美丽。