0

Image that we have some class for example Square.class and an interface Shape with method calculate(). The class Square implements Shape interface and here is my question. In some other class where we have a main method i want to make an instance of square and to use calculate method. What is the difference between this types of instance:

Square square = new Square();
Shape square = new Square();
Metala
  • 43
  • 1
  • 2
  • 8
  • Read up on interfaces https://docs.oracle.com/javase/tutorial/java/concepts/interface.html, then read up on polymorphism https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html – Shar1er80 Jun 07 '15 at 22:44
  • possible duplicate of [Why are variables declared with their interface name in Java?](http://stackoverflow.com/questions/1484445/why-are-variables-declared-with-their-interface-name-in-java) – shmosel Jun 07 '15 at 22:46

2 Answers2

1

When you declare your variable as

Shape square = new Square();

you're programming to the interface, which is a good thing because it decouples the code that uses the variable square from implementation details.

In the future, you might come up with a better implementation of Shape, e.g. EnhancedSquare. When this happens, you don't need to change the code that uses square because your code is not tied to the implementing class (Square).

Mick Mnemonic
  • 7,808
  • 2
  • 26
  • 30
1

The only difference will occur in the bytecode:

Square square = new Square();
square.calculate();

uses invokevirtual to invoke the calculate method,

Shape square = new Square();
square.calculate();

uses invokeinterface.

But both versions invoke the same method.

fabian
  • 80,457
  • 12
  • 86
  • 114