Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Extending Final Classes

Tags:

java

oop

I would like to override a 3rd party, open-source final class's non-final method.

final class A 
{
    void put(obj a)
    {...}

    obj get()
    {...}
}

Please tell me how to override the get() and put() methods, yet still retain the other behaviour and functionality of this class.

like image 336
Kevin Meredith Avatar asked Jan 31 '26 08:01

Kevin Meredith


2 Answers

It's open source: fork it, and make the class non-final.

You won't be able to extend it without making it non-final.

like image 135
Jon Skeet Avatar answered Feb 01 '26 23:02

Jon Skeet


If your class has a defined interface in which put and get methods are defined then You may want to try to proxy the class.

The easiest way is to create something like this:

public interface CommonInterface {

void put(); Object get();

}

final class A implements CommonInterface
{

void put(obj a)
{...}
obj get()
{...}

}

public class ProxyToA implements CommonInterface{

   private A a;

  void put(Object a){
   // your override functionality

  } 

    Object get(){
       // same here
    }

   void otherAStuff(){
        a.otherAStuff();
   }

}

And then just use CommonInterface and proxy your object. Or you can use JDK proxies, javassist, etc.

like image 28
ElderMael Avatar answered Feb 01 '26 23:02

ElderMael