Kevin Meredith
Kevin Meredith

Reputation: 41919

Java Extending Final Classes

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.

Upvotes: 2

Views: 4860

Answers (5)

Sameer
Sameer

Reputation: 4389

The short answer is that you cannot override the methods because you cannot extend the class. What are you planning to do with the get and put methods by overriding? If you are looking add some functionality to those methods, you can create another class which wraps around this class.

Upvotes: 0

Miserable Variable
Miserable Variable

Reputation: 28761

You should definitely try to find out why the class is final. If you are able to convince yourself it is ok to do that, another options is to use AspectJ to just change the behavior of thse two methods.

AspectJ allows you to modify behavior of specific methods. It can do this even for private methods -- security constraints permitting -- and access and assign private fields of the class.

Upvotes: 0

ElderMael
ElderMael

Reputation: 7111

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.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1501926

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.

Upvotes: 13

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45586

You can't extend final class. Per Java spec.

Upvotes: 1

Related Questions