开发者

Java Abstract class implementation

Suppose I have abstract class A and abstract class B which inherits from A, and I create an object of class A as shown:

abstract class A {
   void func1();
}

abstract class B extends A {
   void func2();
}

A objectA = new A() {
   func1(){
      //implementation
   }
};

Is there a way for me to do something like this:

开发者_开发百科B objectB = new B(objectA) {
   func2(){
      //implementation
   }
};

so that objectB gets the implementation of A's functions from objectA?


You can do it this way (via composition, as you won't be able to inherit from the anonymous inner class objectA):

 abstract class A {
    abstract void func1();
 }

 abstract class B extends A {
     A wrapped;
     public B(A objectA) {
         wrapped = objectA;
     }
    abstract void func2();
 }

 A objectA = new A() {
    void func1(){
       //implementation
    }
 };

 B objectB = new B(objectA) {
    public void func1() {
        wrapped.func1();
    }
    public void func2() {
        // impl
    }
 };

AFAIK you can't define a new constructor in objectB, so you are forced to declare it in class B.


I understand what you want to do. Such things are possible in Ruby for example. In Java it's not possible that way because

new A() { 
   func1(){  } 
}; 

is not of type A but an anonymous subclass of A which is not a superclass of B. The compiler generates some $1 class for that.

But in general try another approach: "Favor composition over inheritance". Then are able to combine func1 and func2 somewhere just by using two Strategy classes. So if B is not using any state of A you could delegate to objectA (which has to be final then):

B objectB = new B() { 
   func1(){ 
     objectA.func1()
   } 
   func2(){ 
     //implementation 
   } 
}; 

This is similar to bashflyng's answer, but more direct.


An abstract class is a class that is declared abstract—it may or may not include abstract methods. So if you know one of the (may be default) concrete implementations you may provide implementation of func1() and it can still be abstract. Did not answer your question though (I think answer is NO);


No. Your definition for A is an anonymous class, so there is no way to get that code. There are probably some crazy reflection steps to to make it work, but don't worry about that. If you want to reuse some class definition, make it it's own named class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜