开发者

Inheritance problem Low level Design approach

开发者 https://www.devze.com 2023-03-07 04:25 出处:网络
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 implemen

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 c开发者_JS百科lass X which extends A and is being extended by C and D?

Thanks

Inheritance problem Low level Design approach


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


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.


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*/ }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消