Reputation: 91
Which one is a better practice, doing something like this
public class A {
private B b;
public A() {
b = new B(this);
}
}
public class B {
private A a;
public B(A a) {
this.a = a;
}
}
or extending the class, im really confused about the difference besides having 'a' as a field.
Upvotes: 2
Views: 44
Reputation: 173
it depends what are you going to achieve. Just like Win.ubuntu said use extends in case cat/animal. But if you want to have something like car has an engine then use your second example.
Upvotes: 0
Reputation: 2961
Upvotes: 0
Reputation: 7753
It all depends on particular situation.
Lets assume that A class represents a Car
, then
if B is an Engine
then you should use a composition (Car has an Engine)
if B is a RaceCar
then you should use an inheritance (RaceCar is a better Car)
If in doubt, current trend in software development is to prefer composition over inheritance.
Upvotes: 2