I'm having trouble with the concepts of object oriented programming. Is it better to extend a class or create a new object within a class? Under which circumstances would you extend a subclass versus creating a new instance of that subclass within the calling class? The example is in Java but I imagine the concepts will work in other OOP languages.
I appreciate your insights
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);
}
}
So basically, extends keyword is used to extend the functionality of the parent class to the subclass. In Java, multiple inheritances are not allowed due to ambiguity. Therefore, a class can extend only one class to avoid ambiguity. Implements: In Java, the implements keyword is used to implement an interface.
Extends In Java is a keyword that is written with the child class during class declaration followed by the name of the parent class. When a child class extends a class it acquires or inherits all the properties of the parent class.
Inheritance enables you to create new classes that reuse, extend, and modify the behavior defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class.
Difference: implements means you are using the elements of a Java Interface in your class. extends means that you are creating a subclass of the base class you are extending. You can only extend one class in your child class, but you can implement as many interfaces as you would like.
You extend a class when it has an is-a
relationship. For example, a Cat
is an Animal
. A Cat
is not a CatFood
but it might use CatFood
.
In your case, I'm not sure what MiniMaxi
are, but it doesn't sound like Maxi
is a Mini
, rather it uses one.
In general, try to favor composition (using objects) over inheritance, especially in single inheritance languages like java.
The best answer to that question is another question: does class B use class A or does class B build on class A?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With