<分区>
我对面向对象编程的概念有疑问。 扩展类或在类中创建新对象哪个更好? 在什么情况下您会扩展子类而不是在调用类中创建该子类的新实例?该示例使用 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);
}
}