Use of the generic method and generic class

1, a generic class

package com.wyq.StringBuffer;

public class MyGe<T> {
	//在这里的T只是占位符,并没有表示是什么类型
	public void show(T t){//方法中的泛型T,在差一個年MyGe類的对象的时候就会决定T的类型
		System.out.println(t);
	}
	public <Q> void fun(Q q){//Q类型,在该方法被调用的时候会生效
		System.out.println(q);
	}
	
//	public static void method(T t){
//		/**static静态方法使用泛型会报错
//		 * 报错原因是static静态方法在类加载到内存的时候一同加载,而在这个时候,T的类型还根本没有确定
//		 * 所以这种情况就出现了报错
//		 */
//	}
	public static <E> void method2(E e){//E的类型在访问方法被调用的时候确定 
		System.out.println(e);
	}
	
	public <k> void myMethod(k ... k){//可变参数的泛型方法
		for(int i = 0;i<k.length;i++){
			System.out.println(k[i]);
		}
	}	
}

2, create a generic object

package com.wyq.StringBuffer;

public class TestMyG {
	MyGe<Integer> my1 = new MyGe<Integer>();
	//定义Integer类型
	MyGe<String> my2 = new MyGe<String>();
	//定义为String类型
	MyGe<Person> my3 = new MyGe<Person>();

}

3, the primary method used in a generic

package com.wyq.StringBuffer;

import java.util.Date;

public class TestMyMeth {
	public static void main(String[] args) {
		MyGe<String> my1 = new MyGe<String>();
		my1.show("hello");
		MyGe<Integer> my2 = new MyGe<Integer>();
		my2.show(123);
		my1.fun("world");
		my1.fun(123);
		my1.fun(new Date());
		my1.fun(new Person());
		my2.myMethod("hello");
		my2.myMethod("hello","world");
		my2.myMethod(123);
		my2.myMethod(123,35,4345,2345);
	}
}

to sum up:

When the class is created, use E placeholder to placeholder, and then call back when the object, the type of transfer, transfer what you type what type

You can create static static methods in generic classes, but not the type of static methods and types of the same generic class

Guess you like

Origin blog.csdn.net/wyqwilliam/article/details/93327245