简体   繁体   中英

Why can't I call my Java interface's method?

I have declared the following interface in Java:

public interface ITest {
    void doStuff();
}

which is implemented by another few classes who overwrite the doStuff() method. I then use this interface as the type in a function:

public gonnaDoSomeStuff(ITest fun) {
    fun.doStuff();
}

However, Java (and Eclipse) state that the method is undefined for type ITest. What am I doing wrong?

It turns out that the class containing my gonnaDoSomeStuff method was appended with a generic, which was being referenced instead of the actual interface.

Wrong

public class Dog<ITest> {
    public gonnaDoSomeStuff(ITest fun) {
        // ...
    }
}

Right

public class Dog {
    public gonnaDoSomeStuff(ITest fun) {
        // ...
    }
}

You can not access default declared method in a public class because its scope is limited. You should declared it as public for call in public class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM