0

If I have the (interface animal) and (class dog extends animal) then I create the statement below in main class:

Animal a1 = new Dog( );

What object was actually created? Is it a dog or an animal? Why can we still do this even though an interface can't instantiate an object?

jkdev
  • 11,360
  • 15
  • 54
  • 77

2 Answers2

1
Animal dog = new Dog( );
  • dog - is an instance of Dog object; this is a Dog
  • dog - variable declared as Animal, therefore it provides methods that declared in the interface Animal (Dog object can implement multiple interfaces)

E.g this example;

public interface Animal {
   public String name();
}
public interface SpecialAgent {
   public int agentId();
}
public class Dog implements Animal, SpecialAgent {
   public String name() {
       return "Laika";
   }
   public int agentId() {
       return 666;
   }
}

Demo:

Animal animal = new Dog();
animal.name();    // Laika
animal.agentId(); // not visible for Animal interface

SpecialAgent specialAgent = (SpecialAgent)animal;
specialAgent.agentId(); // 666
apecialAgent.name();    // not visible for SpecialAgent interface;

Dog dog = (Dog)animal;
animal.name();          // Laika
specialAgent.agentId(); // 666
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

It is an instance of Dog while the compiler treats it as an Animal so you could potentially still call the member methods of Dog e.g.

Animal a1 = new Dog();
a1.bark(); // does not work
((Dog) a1).bark(); // works
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107