hello,
i want to know can a member variable of a class can be declared as an intrface type......and if so what is its purpose?
Printable View
hello,
i want to know can a member variable of a class can be declared as an intrface type......and if so what is its purpose?
Yes, it most certainly can, and in fact commonly does. But you must instantiate the object with a class (though this could be an anonymous inner class). For instance we often use the List interface when using ArrayLists like so:
Now if later I decide that my code would run much more efficiently using a LinkedList, I'd not have to change anything in my code except for the constructor call.Code:List<Fu> fuList = new ArrayList<Fu>();
It's called composition or HAS-A relationship.
Its is heavily used in design patterns.
If you put Interface in your class as class member,
you provide encapsulation,
because your class does not need to know
how interface is implemented.
This way you can add more behaviours to your system
at any time, by new implementations, and code in your main class stays the same!
What you have to do is provide implementation of interface in some classes
and then in run-time decide which implementation will you use.
Simple example (not tested :) )
keep on learning this stuff its very useful for advanced codingCode:class A{
private MyInterface job;
public performOperation(){
job.doJob();
}
}
intefrace Myinterface {
public void doJob()
}
class FisrtJob implements MyInterface {
public void doJob() {
System.out.println("doing first job");
}
class SecondJob implements MyInterface {
public void doJob() {
System.out.println("doing second job");
}
/*THIS IS RUNTIME WHERE YOU DECIDE WHICH IMPL WILL YOU USE*/
class JobDemo {
public static void main (String[] args){
A a = new A();
Myinterface job = new FirstJob(); //or new SecondJob
a.performJob(); //this is always the same call
}
}
regards :)
That's a good way of programming.
For example, how do you connect to a database using JDBC? You use interface Connection.
This is useful because if you release a new database product and need to create a driver to it, you can create a class that implements Connection.
If you have a user and what to change the database he uses, he does not need to throw all the code away, just need to change one place and all the rest of the code may work fine!