0

My example shows i try to add some extra method to Runnable anonymous class, in general how can i call extra method which i create.

Runnable myRunnable = new Runnable()
{
    public void run()
    {
        System.out.println("Running");
    }
    // any  extra method to explain the question 
    public void a()
    {
        System.out.println("A");
    }

};
myRunnable.run();
myRunnable.a(); // is this right??
Ahmad Khan
  • 2,655
  • 19
  • 25

1 Answers1

1

Why would you even be able to do such a thing? your myRunnable object is of type java.lang.Runnable. It doesn't have any other methods than what already exists there. Java cannot know at runtime that the actual object which is assigned to myRunnable is actually your own implementation.

However, you can do something like this:

class MyRunnable implements Runnable {
    @Override
    public void run() { }
    public void myMethod() { }
}

And then

MyRunnable mr = new MyRunnable();
mr.myMethod();
Ori Popowski
  • 10,432
  • 15
  • 57
  • 79