Generic definition (2)

The trick of generics not only that. When Dimen object is instantiated, the first time we are using the Integer type, this object is for its various properties, generic functions have become Integer, and when we need to define a Double type of time, we just need a new instance of an object can be.

class Dimen<T>{
	private T x;//向量的x坐标
	private T y;//向量的y坐标
	public void setX(T x){
		this.x = x;		
	}
	public void setY(T y){
		this.y = y;		
	}	
	public T getX(){
		return this.x;
	}
	public T getY(){
		return this.y;
	}
}

public class DimenTest{
	public static void main(String[]args){
		Dimen<Integer> dimen = new Dimen<Integer>();
		//给成员变量赋值
		dimen.setX(5);
		dimen.setY(1);
		//获取成员变量,由于getger的返回值类型是Object,所以需要使用向下转型
		int x = dimen.getX();
		int y = dimen.getY();
		System.out.println("该向量为:" + x + "i" + "+" + y + "j");
		
		Dimen<Double> dimen1 = new Dimen<Double>();
		//给成员变量赋值
		dimen1.setX(5.0);
		dimen1.setY(1.5);
		//获取成员变量,由于getger的返回值类型是Object,所以需要使用向下转型
		double x1 = dimen1.getX();
		double y1 = dimen1.getY();
		System.out.println("该向量为:" + x1 + "i" + "+" + y1 + "j");
	}
}

It is noteworthy that, in the generic type of setting, we can only use the basic data types of packaging or string class, and can not use basic data types.
In the actual development among generics main role is to prevent user error or exception is not in accordance with the provisions of the rules we use to operate due.
Which says just like programmers will Tucao, we are just a Hamburger stalls, you let me tell you a hot pot, there will be a natural bug. The emergence of generics, is to reduce the occurrence of this situation.

Published 15 original articles · won praise 5 · Views 700

Guess you like

Origin blog.csdn.net/weixin_46192593/article/details/104789430