Class & Interface
Hi,
Can anyone clarify few of my questions related to Class and Interface
1.In a Class we can have Interface, how this is useful? and what scenario these is implemented. Please explain.
Eg:
public class NewClass {
public NewClass() {
}
public interface NewInterface {
public void getData();
}
}
2. Similarly we can have Class in a Interface, how this is useful and what scenario these is implemented. Please explain.
Eg:
public interface NewInterface {
class NewClass {
public void getData() {
System.out.println("In GetData Method");
}
}
}
Waiting for ur earilest reply
Think of the java.sql package. It consists largely of interfaces, so you write your code to deal with Connection, Statement and the like. Your JDBC driver vendor will provide actual concrete classes that implement these interfaces, but you don't need to know what they are when writing your code. Interfaces are very handy for allowing you to swap implementations in and out like that. Google "code to an interface" for more info
Just because it's possible it doesn't mean it's useful.
As for those constructs, the same usefulness or uselessness as for a nested class and an interface applies: tie to types to each other that have not much relevance to anyobody else. If you don't want to have to rely on one single implementation, you can introduce that inner interface as well.
class Whatever {
public SpecialList getList() {
// magic
return arrayBasedOrLinkedListBasedList;
}
public interface SpecialList {
void add(Object o);
void remove(int i);
Object get(int i);
}
private class ArrayBasedList implements SpecialList {
// ...
}
private class LinkedListBasedList implements SpecialList {
// ...
}
}