代码之家  ›  专栏  ›  技术社区  ›  Dewfy

Java部分类

  •  7
  • Dewfy  · 技术社区  · 14 年前

    小序言。我是1.4 JDK上的Java开发者。在它之后,我切换到了另一个平台,但这里我遇到了问题,所以问题主要是关于JDK1.6(或更高版本:))。我有3个耦合类,耦合的性质与本机方法有关。下面是这三个类的例子

    public interface A
    {
         public void method();
    }
    final class AOperations
    {
         static native method(. . .);
    }
    public class AImpl implements A
    {
        @Override
        public void method(){ 
            AOperations.method( . . . );
        }
    }
    

    所以有一个接口A,它是由AOoperations以本机方式实现的,AIMPL只是将方法调用委托给本机方法。 这些关系是自动生成的。一切都好,但我有立场的问题。有时接口像需要公开迭代器功能。我可以影响接口,但不能更改实现(aimpl)。

    用c表示,我可以通过简单的部分解决问题: (C样本)

    partial class AImpl{
     ... //here comes auto generated code
    } 
    
    partial class AImpl{
     ... //here comes MY implementation of 
     ... //Iterator 
    } 
    

    因此,Java类似于部分或类似的东西。

    编辑 : 根据@pgras的评论,我需要澄清一下。aimpl不是真空的,有一些工厂(本机实现的)返回aimpl的实例,这就是为什么从aimpl创建继承不适用的原因。

    编辑2 : 可能这与JUnit 4没有关系,但它是如何实现的:

    public class SomeTest {
     ...
     //there is no direct inheritance from Assert, but I can use follow:
     assertTrue(1==1); //HOW DOES it works??
    
    3 回复  |  直到 11 年前
        1
  •  8
  •   Russell Leggett    14 年前

    Java不支持部分或开放类。其他JVM语言是,但不是Java。在您的示例中,最简单的事情可能是不幸地使用委派。您可以让aimpl使用另一个对象来实现这些扩展方法的接口。然后,生成的aimpl将生成迭代器方法等方法,这些方法可以委托给您传入的用户创建的对象。

        2
  •  2
  •   Max Mba    11 年前
    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$.
    

    文件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 };
        }
    }
    

    文件计算$JAVA

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

    文件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;
        }
    }
    

    文件compute$sub.java

    public class Compute$Sub extends Compute$ {
        public Compute$Sub(Compute c) {
            super(c);
        }
    
        public int sub() {
            return $that.a - $that.b;
        }
    }
    
        3
  •  1
  •   pgras    14 年前

    你可以扩展a(比如接口b扩展a),扩展aimpl和实现b(类bimpl扩展aimpl实现b)。