Below is my code...
Its not that much complex.
Here I want to understand that In class D, b is an interface type variable and in that variable we are storing reference to new object of class(C) which implements that interface(B). How we are able to assign object of type C to interface B type variable b..? Class and Interface both are of different types then what makes it special when we implements a interface on class and we are able to do it which is my question
public interface A {
}
public interface B {
public A methodABCD();
}
public class C implements B {
final A typeA;
public A methodABCD() {
return typeA;
}
}
public class D {
static private B b;
static public A methodABCD() {
if (b == null) {
b = new C();-------------->How..?
}
return b.methodABCD();
}
}
Ok lets take an Example and illustrate it.
interface Animal {
public void eat();
}
class Human implements Animal{
public void eat(){
// Eat cakes and Buns
}
}
class Dog implements Animal{
public void eat(){
// Eat bones
}
}
Now let see how you can use them
Animal h = new Human();
Animal d = new Dog();
Now at some point you might want to change your Human to behave like a Dog.
h =d;
h.eat();// Eat bones
Your thought became a possibility because, they belongs to the same type. Imagine that there is not Animal interface and see how difficult it is convert a Human to Dog.
You see the flexibility and the advantages in type varying. You are allowed to do that because of they both are Animal nothing but an Interface.
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