I have an interface Interface1
. I have its implementation Imple implements Interface1
(all methods have been implemented :) ).
Now, consider a third class CheckCall
, can I do a call in the class CheckCall
like I mention below :
Interface1 interface1;
interface1.method();
All necessary imports have been done. Please tell me is it possible or not , if not then ok and if yes, then tell me what will happen if I've more than one implementing classes for the same interface and I'm doing the same call.
In order to call an interface method from a java program, the program must instantiate the interface implementation program. A method can then be called using the implementation object.
There can be only abstract methods in the Java interface, not the method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface.
Interface Methods As mentioned earlier, the interface cannot specify any implementation for these methods. It is up to the classes implementing the interface to specify an implementation. All methods in an interface are public, even if you leave out the public keyword in the method declaration.
Sure, your code works fine! You just have to initialize your variable interface1
with an actual implementation (i.e. new Imple()).
Check out this example, I used your class-names:
public class CheckCall {
interface Interface1 {
void method();
}
static class Imple implements Interface1 {
@Override
public void method() {
System.out.println("Imple.method1()");
}
}
public static void main(String[] args) {
Interface1 interface1;
interface1 = new Imple();
interface1.method();
}
}
Well, you cannot call the method directly on the interface, but you can do what you wrote, more or less.
You wrote:
Interface1 interface1;
interface1.method();
This will work if you do this:
Interface1 interface1 = new CheckCall();
interface1.method();
then tell me what will happen if i have more than one impl classes for the same interface and i am doing the same call
Well, that's the nice thing about Java: the problem you're referring to is called the "diamond problem":
http://en.wikipedia.org/wiki/Diamond_problem
And it doesn't really exist in Java because Java fully supports multiple inheritance, but only through "multiple (Java) interface inheritance" (* see comment).
So in your case when you call interface1.method()
you're either calling Impl
's method or CheckCall
's method and there's no confusion possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With