简体   繁体   中英

Parametric polymorphism in java with simple example

I have researched the topic further and i realise that for an example to purely detail parametric polymorphism, it must not utilise "implements" (which would detail subtype polymorphism) but instead should utilise generics .

This is my previous question: What is parametric polymorphism in Java (with example)?

This is the reworked code to use generics with a single issue.

class Pet<T>
{
  private T pet;

  public Pet(T pet)
  {
    this.pet = pet;
  }

  public String talks()
  {
    // what do i write here?
    // pet.talks(); is undefined for type T
  }
}

class Cat
{
  public String talks()
  {
    return "Meow";
  }
}

class Dog
{
  public String talks()
  {
    return "Woof";
  }
}

public class TestPet
{

  public static void main(String[] args)
  {
    Pet<Cat> cat = new Pet<Cat>(new Cat());
    System.out.println("Cat says " + cat.talks());

    Pet<Dog> dog = new Pet<Dog>(new Dog());
    System.out.println("Dog says " + dog.talks());
  }

}

There is a single issue with my code detailed in comments. I'm unsure how to write it without using the implements command. Do you know what to write?

You need to add an upper bound to T such that it implements an interface which guarantees that there is a talks() method in the type T .

class Pet<T extends Talker>
{
    private T pet;

    public Pet(T pet)
    {
        this.pet = pet;
    }

    public String talks()
    {
        return pet.talks(); // is now defined for type T
    }
}

interface Talker
{
    String talks();
}

Demo, thanks to Ray Toal : http://ideone.com/yiAqM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM