Java generics are polymorphic forms of it?

table of Contents


1. Problem

  • Generics are polymorphic forms of it?

2. Answers

  • No, generics do not recognize multi-state, it is necessary to define what generics enter what class;
  • Polymorphism is describing the relationship between class and class, there must be some object, but did not create generic objects, but objects to limit what type of data can be passed;
  • In the following example, List is not a generic polymorphic polymorphism:
import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<String> ll = new ArrayList<String>;
    }
}
  • Confusing upward generic parameters defined: <? extends 类 >to receive this type of its subclasses, but because polymorphic parent, the object is not involved, so it is not polymorphic, for example:
import java.util.ArrayList;

class People {

}

class Man extends People {

}

public class Test {
    public static void main(String[] args) {
        ArrayList<? extends People> l = new ArrayList<Man>();
    }
}
  • Summary: Generic no polymorphism, polymorphism means that the parent class = variable subclass object, but only a generic label;
He published 189 original articles · won praise 189 · Views 5982

Guess you like

Origin blog.csdn.net/Regino/article/details/104736616