I created an interface and a stack. Now i can call the stack by a reference from that interface or directly as well. I am unable to understand why I should take the reference route. The book I am referring to says its run time implementation so its better. Please can somebody explain it
Asked
Active
Viewed 84 times
0
-
1You need to understand dynamic polymorphism. It is better to post some pseudo code than to explain in plain English. – Ankur Shanbhag Jul 19 '15 at 04:41
1 Answers
0
I'm not sure about the actual code you're referring, but the benefit of using interface is like this.
interface Stack {
void push (T x);
T pop ();
}
class IntegerStack implements Stack<Integer> {
}
As you may see, we can prepare Stack for each types to accepting each types in need, but also access it through same interface. Actually, this decision, which implementation method is called through interface, made by compile-time, so I'm not sure its answering your question.
If you know you only stick to a single implementation, it is useless to use interface. (But it's rare happens the software is developed as a practical use)
Btw, if you're implementing Stack, I believe it's better to use more well-known interface than implementing by yourself. ;)

shinpei
- 393
- 1
- 4
- 15
-
What i mean to say is I create in interface and implement two classes with it. Then i create two objects of the classes respectively, now instead of calling their methods through objects i can call them through the interface reference. Which is to be used in what situation? `public class stackdemo { public static void main(String args[]) { shell1 s; //Interface A ob1= new A(); B ob2= new B(); s=ob1; ob1.fixed(10); ob2.init(15); s.push(5); // Calling via interface s.push(3); s.pop(); ob2.push(11);// Direct calling through object ob2.pop(); } } ` – 1or0_ Jul 19 '15 at 15:32
-
Think another class which has your stack inside. The new class can hold either `A` stack or `B` stack through stack interface. (From your example, it `shell1`) – shinpei Jul 20 '15 at 04:55