Home > other >  Overriding a final method on a final class on an object instance in Java
Overriding a final method on a final class on an object instance in Java

Time:07-12

We're in a situation where we have a class "Base", which has a final toString() method.

We also have a final class "Sub" which extends "Base".

There's a requirement to do a change that's very specific and only applies to a miniscule subset of functionality, but can get pretty intrusive if done "properly".

The easiest way to achieve the change would be to override the toString method on a single instance of the "Sub" class. Creating a new single instance of Sub with the overriden toString() is also an option.

Is this possible to do? Any advice on how to do this?

CodePudding user response:

If you can't change Base class, to remove the final modifier or change the toString implementation to delegate to child class, your best bet would be to add and use interface: have Base and Sub implements the same interface, use the interface everywhere, then do what you need to do using composition:

class Delegate implements CommonInterface {
  private Base delegate;
  //    ctor

  public String toString() {
    return delegate.toString(); // here you are free to change the toString.
  }
}

CodePudding user response:

If any method in java is final, the child classes cannot override the final method. There is only one way if you insist on using toString() in your Sub. Make the toString() of Base class not final.

or

Take a non static final global variable in your Sub class and initialize it using constructor with the required fields to be printed whenever an instance of Sub class need to be printed.

  • Related