简体   繁体   English

从接口访问子类

[英]Access a subclass from an interface

I have an arraylist of an interface named Component.我有一个名为 Component 的接口的 arraylist。 There is another class named Frame that extends component as follows: Component (interface) > AbstractComponent (abstract class) > AbstractContainer (abstract class) > OrganizedContainer (class) > Frame (class)还有另一个名为 Frame 的 class 扩展组件如下:Component(接口)> AbstractComponent(抽象类)> AbstractContainer(抽象类)> OrganizedContainer(类)> Frame(类)

Everything in the component arraylist goes to a renderer to be rendered.组件 arraylist 中的所有内容都进入渲染器进行渲染。 I want to be able to access the methods of the Frame object from the AbstractContainer class.我希望能够从 AbstractContainer class 访问 Frame object 的方法。 Is this possible without declaring the method in the Component interface?如果不在 Component 接口中声明方法,这可能吗?

A Class implements an interface. Class实现了一个接口。 A Class extends another Class.一个 Class扩展了另一个 Class。 An Interface extends another interface.一个接口扩展了另一个接口。 This is the convention in java and I mentioned as in your question you have said your class extends the interface Component .这是 java 中的约定,我在您的问题中提到过您说过您的 class 扩展了接口Component

Frame<<concrete class>> extends OrganizedContainer extends AbstractContainer extends AbstractComponent implements Component<<interface>>

Now coming to your question.现在来回答你的问题。 Is it possible from inside the AbstractContainer Class to access the method which are only defined in Frame ?是否可以从AbstractContainer Class 内部访问仅在Frame中定义的方法? Yes it is possible.对的,这是可能的。 How?如何? In the parent just typecast the (Frame)this.methodInFrame() and to avoid some other sub class object being the currently referred by this , you need to use the instanceof operator.在父级中,只需键入(Frame)this.methodInFrame()并避免其他一些子 class object 当前被this引用,您需要使用instanceof运算符。 so its like所以就像

 if(this instanceof Frame){
     (Frame)this.methodInFrame();
 }

Is it a good practice?这是一个好习惯吗? No not at all, Super class should not be dependent on its sub classes.一点也不,Super class 不应该依赖于它的子类。 This increases coupling in your program and leads to maintenance issues.这会增加程序中的耦合并导致维护问题。 What if you have or plan to have or may have in future any more concrete sub classes?如果您有或计划有或将来可能有任何更具体的子类怎么办? When you modify the Frame your super classes needs to be modified and due to that your newly added subclasses may need modification.当您修改Frame时,您的超类需要修改,因此您新添加的子类可能需要修改。 Also this leads to issues which may be runtime issues.这也会导致可能是运行时问题的问题。 when ever you use instanceof note that it is a code smell, you must have very good reason to use it.当您使用instanceof时,请注意这是一种代码异味,您必须有充分的理由使用它。

The only way to do that is check if the component is of type Frame with component instanceof Frame and then cast the component to Frame .唯一的方法是检查组件是否为带有component instanceof FrameFrame类型,然后将组件强制转换为Frame

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM