Interface

Interface:


  • You can only access the methods defined on the interface through a variable declared as having that interface, even if the concrete class has additional methods. That's why you can call sysout, but not displayName. link
  • It can be use where two subclasses have different type of action  on a single method of superclass.
  • A reference variable can be declared as a class type or an interface type.If the variable is declared as an interface type,
  • A reference variable can be declared as a class type or an interface typw. If the variable is declared as an  interface type than you can access only the method defined in interface from which it is declared.
  • One interface extends other interface.Because one interface contain stubs can extends in only and we could not define its implementation
  • Why an interface can not implement another interface?link

e.g To feed a pet is same for a Bird and a cat. But they have differnent type of food and their style to eat it.
So, in such case we can use an object of interface in super class to solve this problem.

e.g;
Interface for the feeding method: feeding
public interface Feeding {
String feeds(); } class isHarbivor implements Feeding{ public String feeds() { return "Eat plants"; } } class isCarnivor implements Feeding{ public String feeds() { return "Eat both plants and meat"; } }
pet:
public class pets {
public Feeding feedType; private String name; private int number; public void setName( String name){ this.name=name; } public String getName(){ return name; } public void setNumber( int number){ this.number=number; } public int getNumber(){ return number; } public String whatToFeed() { return feedType.feeds(); } public void changeFeed(Feeding feedType) { this.feedType=feedType; } }

Source

More : Link

realted questions
Link

Usage in android:


Java property: Interface reference variable can refer to a subclass object
so here in the above design pattern I can use the reference to call method inside subclass to communicate with other fragment.

0 comments:

Post a Comment

My Instagram