Learn more about Java’s core class library — generic classes

Time:2021-12-4

1.1 use of generics

Generic: parametric model (uncertain, specify type for subsequent use)

1.1.1 generic classes

在这里插入图片描述

1.1.2 generic interface

  • When implementing an interface, you canSelect or deselectSpecifies the generic type

public interface IntercaceName<T>{
	T getData();
}

① Specify type


public class Interface1 implements IntercaceName<String> {
	private String text;
	@Override
	public String getData() {
		return text;
	}
}

② Do not specify type


public class Interface1<T> implements IntercaceName<T> {
	private T data;
	@Override
	public T getData() {
		return data;
	}
}

1.1.3 generic methods

Private static T method name (t a, t b) {}

Method is only valid inside the method

在这里插入图片描述

1.1.4 tips 

  • After compilation, the program will take de genericization measures (generics are only valid at the compilation stage)
  • The runtime generates the corresponding type of the incoming object, that is, the method of type checking and type conversion is added at the boundary of the object entering and leaving the method (the generic type does not enter the runtime phase)

1.2 generic restriction types

  • When using generics, you canappointgeneric Restricted area
  • Must beSubclass of a classor  Implementation class of XX interface, format:

< T extends class or interface 1 & interface 2 >

在这里插入图片描述

1.3 wildcard?

1.3.1 upper limit

  • Refers to the previous session of the generic type (defining the parent class)

< ? extends Parent>

在这里插入图片描述

1.3.2 next session

  • Specifies the next generation of the generic type (subclasses are qualified)

<? super Child>

在这里插入图片描述

1.3.3 unlimited

  • An unrestricted generic type was specified
  • Different from object

1.4 role of generics

  • Improve code reuse rate
  • Types are bound when used, and unordered forced type conversion

summary

That’s all for this article. I hope it can help you and pay more attention to developeppaer!