Reputation: 75
interface MyInterface{
public static int num = 100;
public void display();
}
public class InterfaceExample implements MyInterface{
public void display() {
System.out.println("This is the implementation of the display method");
}
public void show() {
System.out.println("This is the implementation of the show method");
}
public static void main(String args[]) {
MyInterface obj = new InterfaceExample();
obj.display();
obj.show(); // how can i call this ?
}
}
Above is some lines of code , I wanted to know can I call show() method of InterFaceExample class using interface object?. Please help.
Upvotes: 1
Views: 500
Reputation: 448
You need to have an InterfaceExample reference and not a MyInterface reference. The clean way to achieve that is to not assign the InterfaceExample reference to a MyInterface variable; you're throwing type information away. Use an InterfaceExample variable instead.
Alternatively,if there's some reason you have to have a MyInterface variable, then you can cast to an InterfaceExample. You may or may not need to handle the possible resulting exception.
Upvotes: 0
Reputation: 79808
You have three options.
show
method to the interface.obj
to InterfaceExample
.obj
when you want to use a method that's only in InterfaceExample
, for example ((InterfaceExample) obj).show();
The third option here throws an exception if obj
happens not to refer to an object of type InterfaceExample
.
Upvotes: 3