Android development in-depth understanding of the difference between generics extends and super

Source: Internet
Author: User

Summary:

What is a generic type? What is erase boundary? What is an upper bound or a nether qualification (subtype-qualified or super-type-qualified)? What is type safety? What are the uses of the generic extends and super keywords in combination with wildcards ? , and what are the two generics used for real-world Android development?

What is a generic type?

Generics, presumably meaning a class or method that does not specify a specific type, is passed into a class or method in a generic form, uses a pair of angle brackets and an uppercase letter in Java programming (Android programming) representation, for example:

//泛型类public interface List<E>{}//泛型方法,类型参数位于返回类型之前或void之前public static <E> boolean contains(E [] arr, E x){   for(E val:arr){      if(x.equal(val)){         return true;      }   }   return false;}

The contents of the angle brackets are usually denoted by an uppercase letter, but can also be any word or pass in multiple generics at the same time, and its naming convention follows the naming convention of the class name (capitalized), for example:

public interface List<AnyType,A,B,C>{}

In a class that declares an incoming generic, we can consider passing in, or consider not passing in, for example, now we need a list of data (but not the type of explicit data), then the instantiated list can hold various types of data, the code is as follows:

//没有具体类型的列表ArrayList<> mDataSet=new ArrayList<>();         mDataSet.add(new Object());        mDataSet.add(new String());        mDataSet.add(new Integer(0));        mDataSet.add(new Animal());//指定具体类型的列表(存储其他类型,编译不通过,编译器报错)ArrayList<String> mDataSetStr=new ArrayList<>();        mDataSetStr.add(new String());

To better understand the use of wildcards, let's start by setting several classes of inheritance relationships:,,,, and WhiteCuteHelloKitty CuteHelloKitty , for HelloKitty Cat Animal Example:

Wildcards ? can be used either alone or in conjunction with Java Keywords extends or super together, and the differences between them are described later, such as:

  //通配符单独使用ArrayList<?> mDataSetType=new ArrayList<>();  //通配符结合关键字extends一起使用ArrayList<? extends Animal> mAnimalChildren = new ArrayList<>();  //通配符结合关键字super一起使用ArrayList<? super HelloKitty> mAnimalParents = new ArrayList<>();

Here, the use of generics is not listed, and some other uses can refer to other documents to continue our introduction below.

Second, what is erase boundary?

Erase boundary, refers to a specific type, abstract into a generic, then we can write code, according to the actual need to specify the specific type, in line with the dependency of abstract programming ideas . When we write code using the IDE or the Eclipse development tool, the concrete type is substituted for generics at compile time, and it is convenient to use specific types of properties and methods, for example, if we specify a specific class of storage in a list Animal , then we can easily use Animalinternal properties and methods, such as:

    class Animal {        String name;        public void setName(String name) {            this.name = name;        }        public String getName() {            return name;        }    }ArrayList<Animal> mAnimals = new ArrayList<>();//指定ArrayList的泛型具体类为Animal,其对象可以存储Animal及其子类的对象        mAnimals.add(new Animal());        mAnimals.add(new Cat());        mAnimals.add(new HelloKitty());//方便使用Animal内部的属性和方法        String name=mAnimals.get(0).name;               name=mAnimals.get(1).getName();

To put it simply, erasing the boundary is like a square that strips out four sides, becomes a picture without a fixed size without a boundary, and, when needed later, assigns it a specific type, such as a circle, rectangle, triangle or hexagon, a heart shape, and so on.

Third, what is the upper bound or the nether limit?

In a Java program, the most important relationship between a class and a class-the inheritance relationship-is a vertical arrangement of relationships (such as the UML diagram above animal). Upper bounds, which refers to the topmost class that can be found on top (ignoring the object class), and the Nether, which refers to the most terminal class that can be found outside. Generics represent <? extends HelloKitty> all inherited HelloKitty subclasses, so ? the upper bound of the wildcard representation is HelloKitty , but we don't know its lower bound; generics <? super CuteHelloKitty> represent all CuteHelloKitty the superclass, the lower ? bound of the wildcard representation is CuteHelloKitty , In the same vein we do not know its upper bounds. So, beginners in some introduction extends and the super difference in the article, it is easy to extends the upper bound and super of the Nether mixed together to memory, in fact, they have their own upper bound and the lower bound, which is particularly important to note!

Iv. What is type safety?

Type safety, refers to the coding phase, the compiler automatically checks the code, check whether the variable or method calls conform to the current type, if there are non-conformance, the Java compiler will prompt the error, for example, an HelloKitty object mHelloKitty allows the invocation of its own declared or inherited properties and methods, This is type-safe; however, one HelloKitty object mHelloKitty does not allow the invocation of a subclass CuteHelloKitty or WhiteCuteHelloKitty declared property and method, and if it is forcibly invoked, the compiler will prompt the error, which is incompatible with type safety.

To put it simply, the upstream styling is type-safe, and the bottom-up styling is non-conforming to type safety.

Five, wildcard characters?Differences with extends, super keyword use

From the above study, we know that <? extends T> the meaning of the representation is inherited from a set of classes of T, in a generic class List<E> (or method) in the generic type <? extends T> , the compiler will automatically convert to the following code:

//泛型类public interface List<? extends T>{    //泛型方法    boolean add(? extends T e);}

In the example shown below, the Zhao Forest will T replace with Animal a specific class, pass in a generic class, ArrayList<E> <? extends Animal> and then try to save the object to the subclass in the list, and mAnimalChildren finally view the ArrayList Add method, such as:

You will find that the compiler has an error, and it is not allowed to store Animal objects of its own and its subclasses in a list, do I understand the mistake? Why the hell is that?

In the developer's mind, it is naturally easy to understand Animal and Cat conform <? extends Animal> to the generic rules, but for the compiler it is only known that the above generic represents a set of classes, but it is unclear whether it is a specific Animal class or its subclasses, in the ArrayList class, the incoming generics, The compiler will automatically replace the generic in the class, <? extends Animal> such as the Add method, and then boolean add(? extends Animal e) try to pass in the specific class Animal , Cat HelloKitty or, the CuteHelloKitty compiler will be very angry to tell you that: "You do not understand what I said, I ask for?" Extends Animal, but you give me a Animal or its sub-class!! The doubts arose: should I treat it as animal? Or should we treat it as a hellokitty? Or is it treated as cutehellokitty? "Because there is a case of unclear type, the compiler prohibits the developer from passing in the specific type,

This is why the Zhao Forest will take some time to introduce what is the type safety reason, for the compiler requires a type, the developer gave a type B, which is not in line with type safety!

? extends AnimalRepresents a type, Animal Cat or HelloKitty another type, so an error will be indicated!

Since we are not allowed to add data to it, what is the use of generics for ? extends Animal developers? Although the compiler does not allow you to pass data to the Add method.

But for a compiler generic class ? extends Animal , you can be sure that it inherits the properties and methods of Animal , so when we encapsulate the class, we can easily invoke the inherited properties and methods, for example:

    Class Animal {String name;        public void SetName (String name) {this.name = name;        } public String GetName () {return name; }} class Cutehellokitty extends hellokitty{public String feature () {return ' This is a cute Hello    Kitty! ";}}        /** * Package of a class * @param <T> * * class animalname<t>{T e;        Public T get () {return e;        Public T print (T e) {return e; }} public void print () {//-one is bound to a set of classes that inherit from Animal, allowing the use of inherited properties and methods animalname<? extends animal> Animalna        Me=new Animalname ();        Animal Animal=animalname.get ();        System.out.print (Animal.getname ()); Second, bound to a set of Cutehellokitty classes, allowing the use of inherited properties and methods animalname<?        Extends cutehellokitty> cutehellokittyname=new animalname ();        Cutehellokitty Cutehellokitty=cutehellokittyname.get (); System.out.print (Cutehellokitty.feature ()); }

Since generics <? extends Animal> do not fit into the data, developers in the design of the program, for the incoming generic <? extends Animal> class, try to avoid invoking the method to write data, only call the method of reading data. The generic class <? extends Animal> represents all subclasses with the upper bound of animal, unsure of the specific type, which may be traced back to type safety !!

But what if I want to invoke the method that writes the data? So, you might consider using generics, which means <? super T> a set of classes in the lower bound of T, such as:

Take a look at the following example, the compiler allows the developer to do this, the code is as follows:

        //三、绑定为以CuteHelloKitty为下界的一组类        AnimalName<? super CuteHelloKitty> helloKitty = new AnimalName<>();        helloKitty.print(new CuteHelloKitty());        helloKitty.print(new WhiteCuteHelloKitty());

Class, <? super T> for the passed-in CuteHelloKitty class itself and its subclasses, where the compiler automatically traces the shape to Cutehellokitty, which is type-safe, so you can call the Print method that writes the data. The compiler allows the object to pass in the T itself or the T subclass, and eventually the styling is T, which conforms to type safety !!

Summarize:

In a wrapper class to pass in generics, you can specify when encoding the generic to a specific class or a set of classes, specified as a set of classes can consider using wildcards ? and keywords, the extends super generic class <? extends T> represents a set of subclasses bounded by T, suitable for reading data, It is not recommended to call the method that writes the data, otherwise the compiler will give an error; generics <? super T> represent a set of super-classes in the lower bound of T, suitable for calling methods that write data, and not suitable for reading data.

In the development, according to the actual needs of the reasonable choice of incoming <? extends T> , <? super T> or do not use wildcard characters, in line with type safety!!

Android development in-depth understanding of the difference between generics extends and super

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.