Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement method for class in a different class

There is a class A which has an undefined method called OnEvent. I want this method to be define by the class that instantiates a class A Object.

Like this:

public class A{
    int someVar=1;
    float anotherVar=2;

    public void method1(){ 
        ...

        if( event )
            OnEvent();
        ...
    }

    //OnEvent is not defined!!
    OnEvent();
}

And another class, in a different package:

public class B{
    A objA = new A();

    public void method1(){ 
        //I need to do something like
        objA.setOnEvent( this.OnEvent() );
       }

    OnEvent(){
        //Do something
    }

}

I've looked this up and Interfaces and/or lambda expressions are the way to implements this, but I have been unable to do it successfully. Could you please provide some pointers on how to do so?

like image 829
AmiguelS Avatar asked Mar 16 '23 19:03

AmiguelS


1 Answers

You can make the A class abstract (and the OnClick() method abstract, too)`.

Then, you can create anonymous instance(s) of A, with directly providing an implementation for OnClick().

For example:

public abstract class A{
    ...

    public abstract void OnEvent();
}

public class B{
    A objA = new A() {
        public void OnClick() {
            //OnClick implementation
        }
    };
    ...
}
like image 147
Konstantin Yovkov Avatar answered Mar 28 '23 12:03

Konstantin Yovkov