我遇到了面向对象编程概念的问题.扩展类或在类中创建新对象更好吗?在哪种情况下,您是否会扩展子类而不是在调用类中创建该子类的新实例?这个例子是用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);
}
}
Run Code Online (Sandbox Code Playgroud)
当一个类有is-a关系时,你就扩展它。例如,aCat是一个Animal。ACat不是 aCatFood但它可能会使用 CatFood.
就你而言,我不确定MiniMaxi是什么,但听起来不像Maxi是 a Mini,而是使用了一个。
一般来说,尝试使用组合(使用对象)而不是继承,尤其是在像 java 这样的单继承语言中。