We all know that you can't instantiate an interface in Java (directly at least).
But with something like this:
public class Test{
public interface Link {
void mySamplemethod();
String myString ="HELLO!";
}
public static void main(String []args){
Link b;
}
}
What exactly is b... and how could it ever have a practical purpose?
4 Answers 4
b is a variable of type Link that has no value, not even null. In order to have a practical purpose you must initialize it with an object reference whose class implements Link interface.
If you want to initialize Link with a non-null value, you should create a class that implements this interface. That's mandatory in Java. If you don't want to create a new class outside this class, you can create a new class inside the class or inside the method (which would be an anonymous class). Here's a sample:
public static void main(String []args){
Link b = new Link() {
@Override
public void mySampleMethod() {
System.out.println("hello");
}
};
b.mySampleMethod();
}
The purposes of using interfaces for programming instead of direct classes is already explained very well here: What does it mean to "program to an interface"? (no need to reinvent the wheel).
2 Comments
You can create a reference to an interface - you just cannot instantiate it. Let's say for example you have a interface A
public interface A {
public void someMethod();
}
Now you have another class that implements this interface
public class B implements A {
public void someMethod() { // do something }
public void someOtherMethod() { // do something else }
}
Now you can have something like
A a = new B();
While a reference type A it actually implements the method as defined in B. The object type is B. The reference type A indicates that it has only access to those methods in B that are specified by A and nothing else (in this case, it has access to someMethod() and not someOtherMethod()).
Comments
What exactly is b...
b contains a reference to an instance of a class that implements Link. The reference can, of course, be null.
and how could it ever have a practical purpose?
Its practical purpose is pretty much the same as any other Java reference.
Of course, the code as it is does not really put b to any use. However, it's not hard to imagine similar code that would (you'd need to have a class that implements Link, and create an instance of that class).
Comments
For instance interfaces are widely used in polymorphism. So if you have multiple classes implementing interface, you could keep them in the same way:
class One implements Link {..}
class Two implements Link {..}
public static void main(String[] arg) {
Vector<Link> links;
Link link1 = new One();
Link link2 = new Two();
links.add(link1);
links.add(link2);
for (Link l : links) {
l.mySampleMethod();
}
}
bis a reference to an object which must be an instance of class which implementsLinkb = new SubclassOfLink(). If you have no subclasses ofLinkthen you probably had no need to declare the variable.