package day04;
/*
* 模板,将实际类定义交给使用者
*/
public class Generic<T> {
private T x;
private T y;
public Generic(T x, T y) {
super();
this.x = x;
this.y = y;
}
/*
* 模板,将实际类定义交给使用者
*/
public class Generic<T> {
private T x;
private T y;
public Generic(T x, T y) {
super();
this.x = x;
this.y = y;
}
public T getX() {
return x;
}
return x;
}
public void setX(T x) {
this.x = x;
}
this.x = x;
}
public T getY() {
return y;
}
return y;
}
public void setY(T y) {
this.y = y;
}
this.y = y;
}
@Override
public String toString() {
return "Generic [x=" + x + ", y=" + y + "]";
}
public static void main(String[] args) {
/*
* 默认x,y是Object型
*/
Generic<Integer> p1=new Generic<Integer>(1,2);
System.out.println(p1);//Generic [x=1, y=2]
/*
* 虽然默认的是Object型,但是还是会检查
* 不然Integer则报错
*/
//p1.setX("2");//赋值为String型报错
p1.setX(2);
System.out.println(p1.x);//2
/*
* 编译器会做类型转换:int x1=((Integer)p1.getx()).intValue()
*/
int x1=p1.getX();
System.out.println(x1);//2
/*
* 不指定类型,则默认为用原型Object
*/
Generic p2=p1;
System.out.println(p2);//Generic [x=2, y=2]
p2.setX("一");
System.out.println(p1.x);//一
System.out.println(p2.x);//一
//x1=(int) p2.x;
//编译没错,但是运行,编译成.class文件的时候出问题.
//x1为Integer型,p2.x已经为String,类型转换失败
System.out.println(p2.x);//一
}
/*
* 默认x,y是Object型
*/
Generic<Integer> p1=new Generic<Integer>(1,2);
System.out.println(p1);//Generic [x=1, y=2]
/*
* 虽然默认的是Object型,但是还是会检查
* 不然Integer则报错
*/
//p1.setX("2");//赋值为String型报错
p1.setX(2);
System.out.println(p1.x);//2
/*
* 编译器会做类型转换:int x1=((Integer)p1.getx()).intValue()
*/
int x1=p1.getX();
System.out.println(x1);//2
/*
* 不指定类型,则默认为用原型Object
*/
Generic p2=p1;
System.out.println(p2);//Generic [x=2, y=2]
p2.setX("一");
System.out.println(p1.x);//一
System.out.println(p2.x);//一
//x1=(int) p2.x;
//编译没错,但是运行,编译成.class文件的时候出问题.
//x1为Integer型,p2.x已经为String,类型转换失败
System.out.println(p2.x);//一
}
}