Joeav
Joeav

Reputation: 91

Extending or passing as argument

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

Answers (3)

sziolkow
sziolkow

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

Kachna
Kachna

Reputation: 2961

  • Inheritance: Apply the IS-A test.
  • composition : Apply the HAS-A relationship.,

Upvotes: 0

MaxZoom
MaxZoom

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

Related Questions