Java的面向对象,灵活度很大。开发中当不确定某个类的某属性类型时候,可先定义为泛型,实例化该类的时候再具体指明其类型,是非常方便的。今天跟着小编一起看看泛型类怎么操作的吧。
一,自定义泛型类
class Car<T> {
private int price;
private String color;
private T t; //该属性不明确,可定义为泛型,用 T 表示。
public Car() {
}
public Car(int price, String color, T t) {
this.price = price;
this.color = color;
this.t = t;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
@Override
public String toString() {
return "Car{" +
"price=" + price +
", color='" + color + '\'' +
", t=" + t +
'}';
}
}
使用:
public class GenericTest {
@Test
public void test1() {
//定义的泛型类,在实例化时,如果不指明泛型类型,
//则默认泛型为Object
//建议定义的泛型类实例化时,指明泛型类型
Car<String> car = new Car<>();
car.setPrice(100000);
car.setColor("red");
car.setT("china");
System.out.println(car.toString());
}
}
输出:
D:\jdk\jdk1.8.0_171\bin\java.exe
Car{price=100000, color='red', t=china}
二,子类继承有泛型的父类
1,子类具体保留父类的泛型
//Car<String> 此处父类的泛型被指明为String
class MyCar extends Car<String>{
public MyCar() {
}
public MyCar(int price, String color, String businessId) {
super(price, color, businessId);
}
}
使用:
MyCar myCar = new MyCar();
myCar.setPrice(220000);
myCar.setColor("blue");
myCar.setT("jack");
System.out.println(myCar.toString());
输出:
D:\jdk\jdk1.8.0_171\bin\java.exe
Car{price=220000, color='blue', t=jack}
2,子类保留父类泛型,没有指明泛型具体类型
//等价于 class MyCar2 extends Car<Object>{}
class MyCar2 extends Car{
public MyCar2() {
}
public MyCar2(int price, String color, Object o) {
super(price, color, o);
}
}
使用:
MyCar2 myCar2 = new MyCar2();
myCar2.setPrice(1024);
myCar2.setColor("black");
myCar2.setT("mike");
System.out.println(myCar2.toString());
输出:
D:\jdk\jdk1.8.0_171\bin\java.exe
Car{price=1024, color='black', t=mike}
3,子类全部保留父类泛型
//类似于上面的第二种
class MyCar3<T> extends Car<T>{
public MyCar3() {
}
public MyCar3(int price, String color, T t) {
super(price, color, t);
}
}
使用:
MyCar3<String> myCar3 = new MyCar3<String>();
myCar3.setPrice(3322);
myCar3.setColor("green");
myCar3.setT("原谅");
System.out.println(myCar3.toString());
输出:
D:\jdk\jdk1.8.0_171\bin\java.exe
Car{price=3322, color='green', t=原谅}
4,子类继承父类泛型,并且子类自定义属于自己的泛型属性
class MyCar4<E,T> extends Car<T>{
private E e;//子类自定义属于自己的泛型属性
public MyCar4() {
}
public MyCar4(E e) {
this.e = e;
}
public MyCar4(int price, String color, T t, E e) {
super(price, color, t);
this.e = e;
}
public E getE() {
return e;
}
public void setE(E e) {
this.e = e;
}
@Override
public String toString() {
return "MyCar4{" +
"e=" + e +
"} " + super.toString();
}
}
使用:
MyCar4<Integer, String> myCar4 = new MyCar4<Integer, String>();
myCar4.setPrice(22244);
myCar4.setColor("grey");
myCar4.setT("假装");
myCar4.setE(577);
System.out.println(myCar4.toString());
输出:
D:\jdk\jdk1.8.0_171\bin\java.exe
MyCar4{e=577} Car{price=22244, color='grey', t=假装}