java partial classes

夙愿已清 提交于 2019-11-28 12:14:21

Java does not have support for partials or open classes. Other JVM languages do, but not Java. In your example, the simplest thing may unfortunately be to use delegation. You can have your AImpl take another object that fulfills an interface to these extension methods. The generated AImpl would then have generated methods such as iterator methods that it could delegate to the user created object you pass in.

How about that: 
Compute.java  =    your class
Compute$.java  =   base class for partial classes. Reference a Compute object
Compute$Add.java = your partial class. Subclass Compute$.
Compute$Sub.java = your partial class. Subclass Compute$.

file Compute.java

public class Compute {
    protected int a, b;
    Compute$Add add;
    Compute$Sub sub;

    public Compute() {
        add = new Compute$Add(this);
        sub = new Compute$Sub(this);
    }

    public int[] doMaths() {
        int radd = add.add();
        int rsub = sub.sub();
        return new int[] { radd, rsub };
    }
}

file Compute$.java

public abstract class Compute$ {
    protected Compute $that;
    public Compute$(Compute c){
        $that=c;
    }
}

file Compute$Add.java

public class Compute$Add extends Compute$ {
    public Compute$Add(Compute c) {
        super(c);
        // TODO Auto-generated constructor stub
    }

    public int add(){
        return $that.a+$that.b;
    }
}

file Compute$Sub.java

public class Compute$Sub extends Compute$ {
    public Compute$Sub(Compute c) {
        super(c);
    }

    public int sub() {
        return $that.a - $that.b;
    }
}

You could extend A (say interface B extends A) and extend AImpl and implement B (class BImpl extends AImpl implements B)...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!