When can an object reference be cast to a Java interface reference?
April 23rd, 2008When a Java object implements the referenced interface it can be cast to the Java interface reference.
Next: Java interface
When a Java object implements the referenced interface it can be cast to the Java interface reference.
In other words….An interface reference can point to any object of a class that implements this interface i.e. see the example below:
interface Foo{
void display();
}
public class TestFoo implements Foo{
void display(){
System.out.println(“Hello World”);
}
public static void main(String[] args){
Foo foo = new TestFoo();
foo.display();
}
}
Thanks for the nice sample source code Abhishek.
Using anonymous Inner class concept we can create an object for an interface…..
Here is a sample code
interface Sample {
public void method();
}
class Outer {
Sample s = new Sample() {
public void method() {
System.out.println(“Inner class”);
}
};
}
public class Example {
public static void main(String args[]) {
Outer o = new Outer();
o.s.method();
}
}
Output: Inner class
Wow! Thats an excellent example Chandana. Thanks for your contribution.
About chandana’s code,(Sample s = new Sample()) i thought you can’t create an instance of an interface since it has no constructor and creating an instance calls the default constructor.Please advice…great site by the way
Sample s= new Sample(){
// code
};
It doesnt mean that we are creating an Object for Sample Interface…
It means that an object is creating for the class implementing that Sample interface…