简体   繁体   English

用Java中的抽象类定义确切的类

[英]Define exact class from abstract class in Java

I have a class named component that takes a shape Object as a parameter. 我有一个名为component的类,该类将Shape Object作为参数。 The main class which creates an object of component doesn't know exactly which type of shape it's sending to it, all it knows is that it sends an Abstract Shape. 创建组件对象的主类并不确切知道它要发送给它的形状的类型,只知道它发送了抽象形状。 My component however knows it will only get a triangle and therefor use its specific attributes. 但是,我的组件知道它只会得到一个三角形,因此使用其特定属性。

My question, How can I convert the Abstract parameter to a specific subclass of it? 我的问题是,如何将Abstract参数转换为它的特定子类? Example: 例:

public class TriangleHandler extends AbstractHandler{
    //More
    //Code
    //Here
    public tick(AbstractShape shape){
        shape.doTrinagleStuff();
    }
}

public class MainClass{
    private AbstractShape currentShape;
    private AbstractHandler currentHandler;
    //More
    //Code
    //Here
    public tick(){
        currentHandler.tick(currentShape);
    }
}

You can't without casting. 您不能没有演员。 You can only execute methods defined in the abstract class which is ok if you implement it in triangle class with its specific implementation. 您只能执行在抽象类中定义的方法,如果您在带有特定实现的三角类中实现它,则可以。 To be able to run a method that is not defined in abstract you will have to cast 为了能够运行未抽象定义的方法,您必须进行强制转换

Just cast it: 只需投放:

public class TriangleHandler extends AbstractHandler{
    public tick(AbstractShape shape){
        // Since we KNOW it's a triangle, we can cast it
        Triangle triangle = (Triangle)shape;
        triangle.doTrinagleStuff();
    }
}

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

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