Roger
Roger

Reputation: 4259

How are interfaces invoked?

I have an interface containing void doThis();. I've implemented the interface in my Main class and it automatically added public void doThis() { ... } to my class. If I'm in Second class, how do I invoke doThis() in Main?

Upvotes: 0

Views: 88

Answers (4)

Krishan
Krishan

Reputation: 641

new Main(").doThis(); will work. If you want the object to be reused, do like this

InterfaceName obj=new Main();
obj.doThis();
//other things you do with the obj object

Here the thing to remember is, even you can't create objects of interfaces, you can how ever use interface references.

Upvotes: 0

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59111

When you implement an interface, you're making a class. Interfaces are implemented by instance methods on that class.

To invoke an instance method on a class, instantiate the class, and invoke it as you would any other instance method:

Main m = new Main();
m.doThis();

Per my example code, you might want to pass an instance of Main into Second instead of creating the instance inside Second. You can pass this in via the interface instead of via the concrete class type:

public class Second
{
    public void doSomething(SomeInterface si)
    {
        si.doThis();
        // other code here...
    }
}

// Some code outside those classes, that uses both classes...

Second s = new Second();
SomeInterface si = new Main();
s.doSomething(si);

Upvotes: 3

lobster1234
lobster1234

Reputation: 7779

If I understand your question correctly, then

new Main().doThis() 

Upvotes: 3

Will Hartung
Will Hartung

Reputation: 118641

public void methodInSecond() {
    ThingInterface ti = new Main();
    ti.doThis();
}

Upvotes: 3

Related Questions