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.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

2 thoughts on “Java: Are objects of the same type as the interface implemented?”

WordPress › Error

There has been a critical error on your website.

Learn more about debugging in WordPress.