What is printed out in the Java code below – true or false?
public interface Animal { public void sleeps( ); } public class Dog implements Animal { /* ... */ } public class SomeClass { public static void main(String [ ] args) { Dog d = new Dog( ) ; // this checks to see if d is of type Animal if ( d instanceof Animal) System.out.println("true"); else System.out.println("false"); } }
An interface is a type
In order to understand the code above, you must understand that any time a class implements an interface, this means that when an object of that class is created, it will also have the interface type. This means that in the code above, the “d” object will be of both the Dog type and the Animal type. This means that the code above will print out “true”.
Because an interface is a type, we can also create a method with a parameter of an interface type, and that parameter will accept as an argument any class that implements the interface. Here’s an example of that, building on the code above:
public class Dog implements Animal { /*note that this method uses an interface as a method parameter */ public void compareAnimals(Animal x) { /* some code */ } }
In the code above, you can see that the method compareAnimals accepts a parameter of an interface type – “Animal x”, and this is perfectly legal. Any object of a class that implements the Animal class can be passed as an argument to this method.