Friday, June 12, 2015

Java : Excellent Interface Example

 Excellent Interface Example


//Using interface user need not have to think about child parent relation
//any class which implements an interface, can be assigned to that implementing interface instance variable

//Ex: Itree= Interface
//Apple and mango class implements Itree
//Once implemented , I can Use Interface variable to reference both apple and mango
//Also use Interface Array List for looping the same

//Note : Even when there is a new tree ,ex:Strawberry , I can just create a strawberry class implementing Itree and add it to Itree_ArrayList
//this way the code changes is very minimal and I dont need to touch other code.


interface Itree{
public void fruit();
}

class apple implements Itree{
public void fruit() { System.out.println("apple"); }
public void children(){System.out.println("apple a day keeps doctor away"); }
}

class mango implements Itree{
public void fruit() {System.out.println("mango"); }
}




public class tree {
public static void main(String[] args){
ArrayList<Itree> Itree_ArrayList=new ArrayList<Itree>(); // Itree_ArrayList = Interface Array List
Itree tree1=new apple();
Itree tree2=new mango();
Itree_ArrayList.add(tree1);
Itree_ArrayList.add(tree2);
for(Itree t_count:Itree_ArrayList)
t_count.fruit();
apple app=(apple)Itree_ArrayList.get(0);//user can access other methods by casting to apple varibale
app.children();
}
}


Output :
 apple
mango
apple a day keeps doctor away


----------------------------------------------------------------------------------------------------------------------------------

I think it works best for me to create Util library s.But only downside is Static variables are considered to be final.In this case use cannot create getter methods to  change the value of i

public class tree {
public static void main(String[] args){
Itree.static_method();
}
}

interface Itree{
static String i="";
public static void static_method(){ System.out.print("hi"); }
}

Output :
hi