Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically override superclass functions using generics

Tags:

java

generics

If you have a base class that is in a jar file that looks like:

public class A {

public void awesome(int i){

}

}

...which is extended by these classes (also in a jar) as follows:

public class A1 extends A {

@Override
public void awesome(int i){

}

}

and

public class A2 extends A {

@Override
public void awesome(int i){

}

}

...is it possible to override the base function in a generic way?

Say there is an implementation that was being added via anonymous inner class - can you code that such that the entire anonymous inner implementation only appears once? So instead of:

public class Test {

public static void main(String args[]){

    A1 mySpecialA1 = new A1(){
        @Override
        public void awesome(int i){
            //awesome implementation
        }
    };

    A2 mySpecialA2 = new A2(){
        @Override
        public void awesome(int i){
            //awesome implementation
        }
    };
}

}

...you could have (this is where it breaks down):

public class SpecialAFactory {

public static <T extends A> getSpecialA(){
    return new T(){
        @Override
        public void awesome(int i){
            //only once
        }
    };
}

}

So ultimately you would be passing in the subclass that you want to get a new anonymous instance of.

like image 400
hooby3dfx Avatar asked Nov 22 '25 11:11

hooby3dfx


1 Answers

Although you cannot do it with generics, there is a simple, easy to understand, solution that lets you avoid code duplication in cases like that:

public class Test {

public static void main(String args[]){

    A1 mySpecialA1 = new A1(){
        @Override
        public void awesome(int i){
            awesomeImplementation(i);
        }
    };

    A2 mySpecialA2 = new A2(){
        @Override
        public void awesome(int i){
            awesomeImplementation(i);
        }
    };
}

private static void awesomeImplementation(int i) {
    //awesome implementation
}

}
like image 92
Sergey Kalinichenko Avatar answered Nov 23 '25 23:11

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!