nobody
nobody

Reputation: 1949

Inheritance problem Low level Design approach

Suppose I have class hierarchy like the one shown in picture. Suppose I need to include a method doThis() that would have different implementation in classes C and D. But the class B need not implement this method.

Should I declare the contract in Class A and provide an empty implementation in class B or have another abstract class X which extends A and is being extended by C and D?

Thanks Sample Class Diagram

Upvotes: 0

Views: 331

Answers (4)

Adriaan Koster
Adriaan Koster

Reputation: 16209

Do not put it in A if you can avoid it.

The best solution can not be determined from the information you have given us. It depends on the context and meaning of the classes and methods.

Upvotes: 0

Yochai Timmer
Yochai Timmer

Reputation: 49251

If only sub-classes of A will use the method:
Make another abstract class that extend A and adds the method.

If you intend to have that method implemented in different class types:
Make an interface that declares the method, and then C,D should implement that interface as well.

Upvotes: 2

Erhan Bagdemir
Erhan Bagdemir

Reputation: 5327

Make an interface called "doable". let your classes C and D implement this.

public interface Doable {
     public void doThis();
}

public class D implements Doable { /*implementations*/ }
public class C implements Doable { /*implementations*/ }

Upvotes: 1

pickypg
pickypg

Reputation: 22332

Do not put it into class A. Use an interface that is implemented by those that need it.

Upvotes: 3

Related Questions