使几个类具有相同的属性而不继承

时间:2016-12-25 15:28:34

标签: java inheritance

我遇到了Java问题。

我需要有几个具有相同属性的类(例如Position和boolean isWalkable)。

但是我不希望这些类继承类Element,因为这会阻止我以后使用继承。

我想到了一个接口(以便接口具有属性),但显然你不能从一个类继承接口。

必须有办法,否则我必须复制/粘贴我的属性和方法。

提前感谢任何有关如何克服这个问题的人。

3 个答案:

答案 0 :(得分:1)

为此,我会考虑composition over inheritance

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

答案 1 :(得分:0)

您可以扩展抽象基类(不包含任何内容)或者您可以像评论中建议的那样使用Decorator模式,有关Decorator模式的更多信息,您可以阅读此link

答案 2 :(得分:0)

我怀疑你可能需要一个界面,如果你想要一般地对待你的对象 - 例如循环遍历所有这些并绘制每一个。例如。假设你的元素包括" cats"和"房屋":

interface Element{
   public point getPosition();
   public boolean isWalkable();
}
class Cat implements Element{
   private Point position;
   private String catBreed; // example of cat-specific data
   public point getPosition() {return position;}
   public boolean isWalkable() {return true;} // cats can walk
   ...
}
class House implements Element{
   private Point position;
   private String streetAddress; // example of house-specific data
   public point getPosition() {return position;}
   public boolean isWalkable() {return false;} // houses cannot walk  
   ..
}

// Finally, using that common interface:
Element[] allGameObjects= {new Cat(...), new Cat(...), new House(...) };
for(Element e:allGameObjects) 
   draw(e, e.getPosition());

对于我写的几个系统来说这已经足够了......但正如其他回复中正确提到的那样,你可能会重构使用组合 - 但它可能不是100%明确的。我的意思是,我能理解你是否觉得Cat或House应该独立于他们的位置进行管理......但是,是什么呢?

// Position is easy to separate:
class Cat { String catBreed; ... }
class House{ String streetAddress; ... }

class ElementWrapper implements Element{
   Point position;
   Object  theObject; // could hold Cat or House
   public Point getPosition() {return position;}
   // however, isWalkable is a bit tricky... see remark below
}

但是' isWalkable'很棘手,因为在经典的多态性中,你期望House / Cat告诉你他们是否可以走路(意味着他们应该实现一个接口)。如果你绝对不想要(或者不能)拥有它,你可能会在多态性上做出妥协,并在instanceof的行中做一些事情(如果对象是cat的,那么它可以走,如果它是它的实例,它不能走路等。)