简体   繁体   中英

Java generics and polymorphism

What is polymorphism in java? I am trying to understand this with generics. Let us consider the following class Pair.

public class Pair<X, Y>
{ 
      public final X x; 
      public final Y y; 

      public Pair(X x, Y y) { 
        this.x = x; 
        this.y = y; 
      } 
}

If we want to instantiate the class then we are doing to do something like this:

Pair <String, int> pair = new Pair<>("one", 1);

Now because i am using String and int instead of X and Y can i say this is polymorphism? There is also this concept of super classes and polymorphism. What about that?

Generics

What you see here are generics . It has nothing to do with polymorphism.

Generics are something like an argument is for a method:

public static void foo(int bar) { ... }

The method foo wants a user to give it some int value when it is called. The method itself refers to that value by the local variable bar . A call might look like

foo(5);
foo(8);

If you have a generic class like

public class Pair<A, B> { ... }

the class Pair wants the user to declare two types when using it. The class refers to them by the placeholders A and B . So one might use it like:

Pair<String, Integer> stringAndInteger;
Pair<Dog, Car> dogAndCar;

The nice thing about it is that the compiler can use this information to ensure that dogAndCar can really only be used with Dog and Car for A and B . So if the class has a method like

public void setFirst(A first) { ... }

you can not call the method with the wrong type, like dogAndCar.setFirst(10); . The compiler knows A is Dog for dogAndCar and will not allow that you use it with anything that is not Dog .

For more on the topic, read the official tutorial for generics.


Polymorphism

Polymorphism refers to the concept of one class implementing features of a parent class but overriding some other or adding new functionality.

Let's consider the following parent class

public class Animal {
    public void makeNoise() {
        System.out.println("Hello");
    }
}

Now we extend that class and override the method. Additionally we add a second method:

public class Dog extends Animal {
    @Override
    public void makeNoise() {
        System.out.println("wuff wuff");
    }

    public String getName() {
        return "John";
    }
}

If we use the makeNoise method on a Dog , we will see "wuff wuff" and not "Hello" .

For more on this take a look at the official tutorial on polymorphism.

Note that you can further distinguish this into inheritance and polymorphism . Read What is the main difference between Inheritance and Polymorphism? for more.

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