1. 泛型类使用
package com.denganzhi.fangxing;
/***
* 泛型类: 申明时使用泛型
* 字母:
* T key 表示类型
* E,V 分别代表键值中的key value
* E: 代表元素
*/
class Student<T1,T2> {
private T1 username;
private T2 age;
public T1 getUsername() {
return username;
}
public void setUsername(T1 username) {
this.username = username;
}
public T2 getAge() {
return age;
}
public void setAge(T2 age) {
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
// 使用的时候指定类型(引用)
/** 注意
* 1.泛型在使用的时候,不能使用基本类型
* 2.泛型在使用的时候不能使用 静态属性|静态方法上
*/
Student<String, Integer> stu=new Student<>();
stu.setAge(100);
}
}
2. 泛型接口使用
package com.denganzhi.fangxing;
/**
*
* 泛型接口使用
*/
public interface Comparator1<T> {
void compare(T t);
}
3. 泛型方法
package com.denganzhi.fangxing;
public class TestMethod {
public static void main(String[] args) {
// 调用方法
test(33);
}
// 泛型方法
// 只能访问对象的信息,不能修改,对象不确定 <=
public static<T extends Integer> void test(T a){
System.out.println(a);
}
}
4. 泛型与继承| 接口使用使用
package com.denganzhi.fangxing;
/**
* 1. 实际使用中 第一种方式
* 2. 第二种方式
*/
public abstract class Father<T> {
T name;
public abstract void test(T t);
}
//1. 子类使用时候 父类确定具体的类型
class child1 extends Father<String>{
@Override
public void test(String t) {
// TODO Auto-generated method stub
}
}
// 2. 子类为泛型类,继承父类泛型
class child2<T> extends Father<T>{
@Override
public void test(T t) {
// TODO Auto-generated method stub
}
}
// 3. 子类为泛型,父类不指定类型,泛型擦除,使用object替代
class child3<T> extends Father{
@Override
public void test(Object t) {
// TODO Auto-generated method stub
}
}
// 子类和同时擦除
class child4 extends Father{
@Override
public void test(Object t) {
// TODO Auto-generated method stub
}
}
//错误, 子类擦除,父类使用泛型
//class child5 extends Father<T>{
//
//}
5. 泛型的嵌套:
package com.denganzhi.fangxing;
class Student2<T>{
T score;
}
class Bjsxt<T> {
T stu;
}
public class TypeNest{
public static void main(String[] args) {
// 泛型嵌套
Bjsxt<Student2<Integer>> bjsxt=new Bjsxt<Student2<Integer>>();
// 使用的时候从内到外拆分
bjsxt.stu=new Student2<Integer>();
Student2<Integer> stu2= bjsxt.stu;
stu2.score=100;
Integer score = stu2.score;
System.out.println(score);
Object str="xiaoming";
if(str instanceof String){
System.out.println(str);
}
}
}
6. 泛型与多态
package com.denganzhi.fangxing;
/**
* 泛型与多态
*/
abstract class Animal{
abstract void showAnimal();
}
class Dog extends Animal{
@Override
void showAnimal() {
System.out.println("dog");
}
}
class Cat extends Animal{
@Override
void showAnimal() {
System.out.println("cat");
}
}
class Student1<T>{
T t1;
}
public class MultiTypeMain {
// ? 不确定类型
public static void showDog1(Student1<?> stu){
}
// ? <= Animal
public static void showDog2(Student1<? extends Animal> stu){
}
// ? >= Animal
public static void showDog3(Student1<? super Animal> stu){
}
// 使用的时候
public static void main(String[] args) {
showDog1(new Student1<Object>());
showDog2(new Student1<Dog>());
showDog3(new Student1<Animal>());
}
}