1

I have the next question. I have interface

public interface MyInterface {
    blah blah
}

And I have child:

public class MyChild implemets MyInterface {
    blah blah
}

What is the difference between:

MyChild child = new MyChild();

and

MyInterface child = new MyChild();

?

Razib
  • 10,965
  • 11
  • 53
  • 80
ovod
  • 1,118
  • 4
  • 18
  • 33

2 Answers2

3

Your added code snippet is -

MyChild child = new MyChild();  

and

MyInterface child = new MyChild();  

In first case child can contain only the object of MyChild class. But in the second case child (where child is a MyInterface) can contain all object of those class that implements MyInterface. Here you can get the advantage of polymorphism.

Razib
  • 10,965
  • 11
  • 53
  • 80
1

When you do:

MyInterface child = new MyChild();

you are doing what is called "coding to an interface" and it allows you to respect the Open Closed Principle: Open for extension but closed for modification. This allows you to leverage dynamic polymorphism.

  • Creating an instance of a class has nothing to do with the _open/closed principle_ this is a matter of design. – tomse Mar 28 '15 at 21:21
  • @tomse, of course it is. Don't try to find problems where they don't exist. I had to paste that bit of the post to illustrate which statement adhered to coding to an interface. The fact that it is a object creation statement is by the by! –  Mar 28 '15 at 21:24
  • Ok, maybe I misunderstood your intention a bit since the _open/closed principle_ is nothing the user of a class should have to take care about, instead the creator of a class should ensure that its implementation of an interface is in line with this principle. So for this question the _open/closed principle_ is not relevant and IMO more confusing than helpful... – tomse Mar 28 '15 at 21:54