非常先进的方法/构造函数(Java) - 接受真正的多态参数 - 语法

时间:2012-12-02 13:40:24

标签: methods arguments instanceof polymorphism implements

有没有办法声明多态构造函数? (请不要超载!)。

我想指定一个类似于1个类和1个接口的参数但我不想创建一个具有这两个类的新类(类实现接口)。

我想声明一个构造函数,通常使用语法:

class Clas {
  public Clas(Object obj) { ... }
}

但是这些参数“obj”是Class1和Interface2的实例,我想这样:

class CubeRotationThread {
  public CubeRotationThread(Cube c implements IRotable) {...}
  //...or...
  public CubeRotationThread(Cube c instanceof IRotable) {...}
}

...或仅为此参数指定多态的任何其他语法。我不想创建类:CubeRot extends Cube实现了IRotable,因为并非所有的多维数据集都有这些功能。而且我不想要另一种选择(Cube)CubeRot,反之,使所有立方体可旋转。 也许IRotator可以在立方体或其他类中实现或不实现。

我不想在构造函数中使用check:

if (obj instanceof Class) { myMethod(); }

我不想创建新类

class CubeRotatorThread extends Cube implements IRotator {
}

...因为并非所有立方体都可以旋转,不仅立方体实现了旋转。

我不想使用泛型类:

class CubeRotatorThread T extends Cube implements IRotator {
}

...因为T是一个类,我想要一个对象/参数。

我也不想创建NotImplementsRotationException!投掷。

我想要一个多态参数,我想要一个真正的多态方法

有可能吗?我搜索了它,但是我没有在构造函数中找到这样做的语法。

我在其他语言(可能是C#或C ++)的其他代码中看到了帮助文档或定义文档,例如:

Constructor(Class1 (Class2) args);

这对我来说很奇怪。而且我不确定这是我想要的。

如果多态构造函数不存在,我认为Oracle必须创建它。这非常有用。

class CubeRotationThread {
    public CubeRotationThread(Cube arg implements IRotator) {}
    public CubeRotationThread(Cube arg extends IRotator) {}
    public CubeRotationThread(Cube arg instanceof IRotator) {}
}

1 个答案:

答案 0 :(得分:0)

GENERIC METHOD
http://docs.oracle.com/javase/tutorial/java/generics/bounded.html
http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html
http://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html

I FOUND IT ! :)

    public <Q extends Class1 & Iterf2 & Interf3> Return Method(Q Object) { }

Q is the private mixture class you want with Extends & implements & implements...

here is with multiple objects:


    public <Q extends Class1 & Iterf2 & Interf3, W extends Class2 & Inter1 & Inter2> Return Method(Q arg1, W arg2) { }



use commas to separate classes inside <>, and use & to inherit

use commas to inherit directli in a class declaration


Here is very complete:

    class Generic extends String implements Implements1, Implements2 {}

    class Generic <T extends Class1 & Interface1 & Interface2> extends Class2 <W extends 

    Class3 & Iterface 5> implements Interface3, Interface4 {
            public <Q extends Class2 & Interface4, R extends Class4 & Interface6> Generic(T wtf, Q arg, R arg) { }
        }