我对面向对象编程的概念感到困惑。
在一个类中,扩展一个类或创建一个新对象哪个更好?
在什么情况下会扩展子类而不是在调用类中创建该子类的新实例?示例是在Java中,但我想这些概念也适用于其他面向对象编程语言。
我感谢您的见解。
我感谢您的见解。
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);
}
}
Car
的类和两个子类Mercedes
和BMW
,你应该继承,因为你需要在两个子类中使用超类的方法。但是,如果这些类没有像我的例子那样的关系,你可以像你所做的那样简单地编写代码:class Maxi { Mini myMini = new Mini(5); ...
- Leviathan