java - 面向对象的Java : Better to extend a class or create a new instance of the subclass?

标签 java oop

<分区>

我对面向对象编程的概念有疑问。 扩展类或在类中创建新对象哪个更好? 在什么情况下您会扩展子类而不是在调用类中创建该子类的新实例?该示例使用 Java,但我想这些概念也适用于其他 OOP 语言。

感谢您的见解

class Mini {
// I want to use the members of this class in another class
    int myInt;

    public Mini(int myInt){
        this.myInt = myInt;
    }

    public int myMethod(){
        return this.myInt;
    }
}

// should I create a new instance of Mini here?
class Maxi {
    Mini myMini = new Mini(5);

    public Maxi(){
        int miniInt = myMini.myMethod();
        System.out.print(miniInt );
    }
}

// or should I have Maxi extend Mini?
class Maxi extends Mini {
    public Maxi(int myInt){
        System.out.print(this.myInt);
    }
}

最佳答案

当类具有is-a 关系时,您可以扩展它。例如,CatAnimalCat 不是 CatFood 但它可能使用 CatFood

在你的情况下,我不确定 MiniMaxi 是什么,但它听起来不像是 MaxiMini,而是它使用一个。

一般来说,尽量支持组合(使用对象)而不是继承,尤其是在像 java 这样的单继承语言中。

关于java - 面向对象的Java : Better to extend a class or create a new instance of the subclass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19641899/

相关文章:

java - 通过反射创建包含匿名内部类的类的对象

c# - 不明确的构造函数调用错误

c# - 从Java转换为C#:用于重新编码字符串的简单代码

javascript - ES6 调用静态方法抛出错误

php - 如何更改导入类使用的类的命名空间?

java - 更新对象的方法的返回类型分析

c++ - 使用来自 unique_ptr vector 的原始指针作为排序的 ID

java - 引用和使用另一个类的数组

Java- 使用 http 协议(protocol)通过网络发送数百万条记录的最佳方法

Java 日期验证