user8118329
user8118329

Reputation:

Class implements Interface

So I started learning Interfaces and now I'm wondering when to use

Interface i = new Class();

and when to use

Class c = new Class();

and I noticed that I can't use class methods if I do it the first way, only interface methods. Do you know why?

Sorry I'm still a noob in Java, Thanks for answering

Upvotes: 0

Views: 104

Answers (2)

Pavan
Pavan

Reputation: 858

Let me put it in simple way.

Interface defines the behavior of class and classes which implements interface will give implementations to that behavior.

Here is an example

Interface Shape
{
 void draw();
}

Class Circle implements Shape
{
   void draw()
  {
    ... code to draw circle
  }

   void printRadius()
  {
  }
}

Class Rectangle implements Shape
{
   void draw()
  {
    ... code to draw rectangle
  }

   void printDiagonal()
  {
  }
}

now if you see same Shape Interface is implemented by 2 classes diffrently.

Now i can write like this

Shape shape = new Circle(); // This will allow you access only draw method
Circle circle = new Circle(); // This will allow you access all methods of circle

When you want your client/consumer to access only Shape specicfic methods like draw then use Shape shape = new Circle() else if you want Circle specific method such as printRadius then use Circle circle = new Circle()

Upvotes: 1

Artem Barger
Artem Barger

Reputation: 41232

The interfaces in OOP paradigm used to generalized common behavior across group of somewhat similar objects. Therefore then you using variable of more general type, e.g. interface you will be able to use only those common methods which interface defines. Since you should be able to assign to interface variable any of interface descendants (classes which implements given interface) and be able to work with it. Therefore while you assign

Interface i = new Class();

the only methods you will be able to access is those defined in the Interface. Additionally need to note, that variable will be dynamically binded to the runtime type, e.g. to the Class in your example, thus the calls for methods defined in you interface will be dispatched to the implementation of the class.


Also think of the following, for example you have definitions:

interface Vehicle {
     public void drive();
     public void stop();
}

Now if you write code:

Vehicle v = new BMW()
v.drive()
// do something else
v.stop()

it should behave same when you replace new BMW() with new Mitsubishi(), regardless the fact that probably in your BMW class you might have

class BMW {
    public void listenMusic()
}

This is also called "Liskov substitution principle"

Liskov's notion of a behavioral subtype defines a notion of substitutability for objects; that is, if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program.

Upvotes: 0

Related Questions