user3161041
user3161041

Reputation: 13

Polymorphism - correct understood? (JAVA)

I have been reading about polymorphism and would like to ask, if this is a correct example of polymorphism:

Interface:

public interface Language {
  public void talk();
}

Two different classes that inherit it:

public class Jimmy implements Language{
  public void talk(){
    System.out.println("Jimmy talks English");
  }
}

public class David implements Language{
  public void talk(){
    System.out.println("David talks Spanish");
  }
}

Class to run:

public class RunProgram(){
  public static void main(String [] args){
    Jimmy j = new Jimmy();
    David d = new David();
    j.talk();
    d.talk();
  }
}

The output should be:

Jimmy speaks English David speaks Spanish

The idea of this is that the talk method is inherited from the interface and that the two classes (rather objects) determine what the output exactly is, so the output depends on which object you create and run the method from. Sorry if I am asking something that might be easy, and this example may not even be that good but I hope that it can illustrate my idea. Thanks in advance!

Upvotes: 0

Views: 82

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200296

Jimmy j = new Jimmy();
David d = new David();
j.talk();
d.talk();

No, there's no polymorphism involved in the above code. Delete the interface Language and the code won't even notice.

The way to demonstrate polymorphism in action must involve the interface as the static type of the variables:

Language j = new Jimmy(), d = new David();
j.talk();
d.talk();

However, an example which truly showcases polymorphism as a useful language feature arises when you involve a method written against the interface type:

public void printTheTalk(String name, Language lang) {
   System.out.println(name + " says " + lang.talk());
}

Now you can see how that method has no idea of even the existence of the concrete type of the objects, yet it can work with them.

Upvotes: 4

rgettman
rgettman

Reputation: 178333

This is close. The point of polymorphism is that you can have a reference to an interface or superclass, which doesn't care which concrete class (Jimmy or David) the object really is.

If you were to use

Language j = new Jimmy();
Language d = new David();

then this demonstrates polymorphism. The variables j and d only care that they are Languages, but the specific implementation of talk() is called later.

Upvotes: 1

Related Questions