Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Call method not defined in interface from implemented interface in Java

I have the following scenario in Java. Let's say I have an interface, and two classes that implement this interface. As follows:

public interface myInterface {

    public String printStuff();

}

public class A implements myInterface {

    @Override
    public String printStuff(){
        return "Stuff";
    }
}


public class B implements myInterface {

    @Override
    public String printStuff(){
        return "Stuff";
    }

    public String printOtherStuff(){
        return "Other Stuff";
    }
}

How do I call the printOtherStuff method above if I define it as follows:

public static void main(String... args) {
 
     myInterface myinterface = new B();
     String str = myinterface.printOtherStuff(); // ? This does not work
}

The above calling code does not seem work. Any ideas?

question from:https://stackoverflow.com/questions/65913391/how-come-i-cant-access-the-class-methods-of-interface-type-variable-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
myInterface myinterface = new B();

The reference type of myinterface is myInterface. That means you can only access the methods defined in the interface. You can cast it to type B in order to make the method call.

NOTE: From here on out I'll be using the proper naming conventions.

Example

MyInterface myInterface = new B();

String str = ((B)myInterface).printOtherStuff();

Just a note on this

If you need to do this, then you need to have a look at your class design. The idea of using an interface in this way is to abstract away from the details of the object's concrete implementation. If you're having to perform an explicit cast like this, then you might want to look into either changing your interface to accommodate the necessary methods, or change your class so that the method is moved into a global location (like a util file or something).

Extra Reading

You should read about reference types here, and you should have a look at casting here. My answer is a combination of the understanding of both of these things.

As an added note, take a look at the Java Naming Conventions. This is a vital piece of information for any Java developer to make understandable code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...