开发者

Superclass has subclass reference

I have a situation where I have to put getters and setters for a sublass reference in superclass. I just need to know whether its a good practice or not?

I have given the code below.

public class SuperClass{
 String commonProperty;
 private BaseClass baseClass;

 public void setBaseClass(BaseClass baseClass){
  this.baseClass = baseClass;
 }

 public BaseClass g开发者_如何学编程etBaseClass(){
  return this.baseClass;
 }

}


public classs BaseClass extends SuperClass{
 String uncommonProperty;



}


It's a code smell that something is wrong with your design. As @Ben said, we don't know your specifics. But since you're asking the question I'm guessing that you feel that there is something wrong. And you're right about that.

To reiterate, a subclass inherits from a superclass, thus by the fundamental way OO languages work, you should not need that kind of referencing.


In general this is bad practice, because a superclass should not have to know who is extending it. Also, this only limits you to one subclass. You can use reflection to find all subclasses, but that's also typically an indicator of a bad design.

Without knowing specifics, I'm tempted to think that you don't really need to do this.


This is no best coding or design practice as the Super class does not need to no anything of its subclasses, it is only the subclasses which must know about the superclass

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜