When can an object reference be cast to a Java interface reference?

April 23rd, 2008

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();
}

}

Abhishek Khandelwal on November 3rd, 2009 9:40 pm

Thanks for the nice sample source code Abhishek.

Joe on November 5th, 2009 8:02 am

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

chandana on November 11th, 2009 7:45 pm

Wow! Thats an excellent example Chandana. Thanks for your contribution.

Joe on November 11th, 2009 9:37 pm

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

macfusion on December 17th, 2009 11:12 am

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…

chandana on January 13th, 2010 3:12 pm





hidden and gravatar enabled.