User User - 2 months ago 6
Java Question

Can I remove a method from a class instance in java?

Lets say I have a class called 'Foo', with some methods:

public class Foo{
public void a(){
//stuff
}

public void b(){
//stuff
}
}


And i have an instance of Foo:
Foo instanceOfFoo = new Foo();


Can i remove the method 'a' from 'instanceOfFoo'?

Answer

You can't remove a method, not without changing the byte code and breaking the code's "contract", but you could extend the class and have the child class's method override throw an UnsupportedOperationException if called. Also the child class should deprecate the method, and explain in its javadoc the rationale behind it, and what to use in its place.

This would change the class's contract, but in a more responsible way then say fiddling with the byte code.

For example:

public class Foo {
    public void a() {
        // stuff
    }

    public void b() {
        // stuff
    }
}

public class FooChild extends Foo {
    /**
     * @deprecated: This method should no longer be used and will throw an exception
     */
    @Override
    @Deprecated
    public void a() {
        String text = "The method a is no longer supported";
        throw new UnsupportedOperationException(text);
    }
}