【问题标题】:Right way to design using oop and multiple-inheritance in java在 java 中使用 oop 和多重继承进行设计的正确方法
【发布时间】:2019-03-05 03:48:24
【问题描述】:

假设我们有一家商店,我们销售 3 种产品。 我们出售糖果、篮子和礼物。

所以客户可以购买:

  • 糖果
  • 篮子
  • 礼物(礼物被定义为一个篮子,里面装满了糖果,外加一条装饰丝带)

我想使用 java 继承来实现这一点,所以我做了以下事情:

public class Candies {

    private int weight;

    public Candies(int weight){
        this.weight = weight;
    }

    //setters & getters
}

public class Baskets{

    private String color;
    private int weight;

    public Baskets(String color, int weight){
        this.color = color;
        this.weight = weight;
    }

    //setters & getters
}

public class Present {

    private String ribbon_color;

    //....
}

现在的问题是,当客户想要购买礼物(包含糖果、篮子和丝带)时,我需要一个单独的 Present 类来创建 candybasket 对象。我知道在 java 中不允许多重继承,所以我被困在如何实现这一点上。

我可以将糖果和篮子定义为接口,并有一个实现这两个接口的 Present 类,但这是最有效和正确的方法吗?

【问题讨论】:

  • “我想用java继承来实现这个……” 为什么?这不是继承的用例。这是一个类型属性的用例,也可能是聚合。
  • 我不知道您是否需要针对不同种类的产品使用单独的类(而不是拥有具有许多属性的 class Product 可以处理所有这些属性并由这些属性的数据库驱动) -- 这将允许您在不更新代码的情况下添加或修改产品)。但是,如果您想这样做,Present(或者可能是 Basket)让我印象深刻,因为它自己的属性是其他产品的 容器,即有一个字段可以保存零个或多个其他产品的实例。此处无需建立子类关系。
  • 在您的情况下,组合应该优先于继承。 en.wikipedia.org/wiki/Object_composition

标签: java oop interface multiple-inheritance


【解决方案1】:

我认为您可以在 Candies、Baskets 和 Presents 的每个类中创建 Id。

然后您可以创建的项目包括:Id、cate(Id 用于保存 Candies、Baskets、Presents 的 Id;cate 以阐明此项目在 Candies、Baskets 或 Presents 中)。

像这样:

public class Candies {

    private int Id;
    private int weight;

    public Candies(int Id, int weight) {
        this.Id = Id;
        this.weight = weight;
    }


    //setters & getters
}

public class Baskets{

    private int Id;
    private String color;
    private int weight;

    public Baskets(int Id, String color, int weight) {
        this.Id = Id;
        this.color = color;
        this.weight = weight;
    }

    //setters & getters
}

public class Present {

    private int Id;
    private String ribbon_color;

    public Present(int Id, String ribbon_color) {
        this.Id = Id;
        this.ribbon_color = ribbon_color;
    }

    //setters & getters
}

public class Items {

    private int Id;
    private String cate;

    public Items(int Id, String cate) {
        this.Id = Id;
        this.cate = cate;
    }

    //setters & getters
}

现在,您可以使用商品列表购物。

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-24
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    相关资源
    最近更新 更多