Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type of object while implementing interface

Tags:

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();
  }
}
like image 484
LearnJava Avatar asked Jul 05 '17 04:07

LearnJava


1 Answers

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.

like image 108
Suresh Atta Avatar answered Oct 12 '22 08:10

Suresh Atta