Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Override a foreign method

I'm trying to make a spcial add-ons for my application. I need to override some methods of a class without editing the class file.

Here is a scheme:

class A
{
    public void method1()
    {
        // Do something here
    }

    public int method2()
    {
        // Do something
    }
}

Now from my class B, I want to override the method1 func from the class A, and force the A class to use my new method.

class B
{
    public void method1()
    {
        Do something
    }
}

I want to update my class A code without editing the A class. Is that possible?

Thanks.

like image 926
Manitoba Avatar asked Nov 29 '25 05:11

Manitoba


1 Answers

use class B extends A and ovverride method that you want to change. how ever you have to use instance of class B not A. like

class B extends A
{
    public void method1(){
      Do something
    }
}
A a = new B();
a.method1();
like image 86
Nirmal- thInk beYond Avatar answered Dec 01 '25 19:12

Nirmal- thInk beYond



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!