类的使用
父类:Animal
子类:Dog、Cat
测试类:Test01
Animal类
package fanxing;
public class Animal{
private String name;
//无参构造方法
public Animal(){
super();
}
//有参构造方法
public Animal(String name){
this.name = name;
}
//set方法
public void setName(String name){
this.name = name;
}
//get方法
public String getName(String name){
return name;
}
//say方法
public void say(){
System.out.println(name);
}
}
Dog类
package fanxing;
public class Dog extends Animal{
//继承的无参构造方法
public Dog(){
super();
}
//继承的有参构造方法
public Dog(String name){
super(name);//继承父类有参构造方法,super关键字内要加参数
}
//重写父类的say方法
public void say(){
super.say();
System.out.println(getClass().getName());
}
}
Cat类
package fanxing;
public class Cat extends Animal {
//继承的无参构造方法
public Cat(){
super();
}
//继承的有参构造方法
public Cat(String name){
super(name);
}
//重写父类的say方法
public void say(){
super.say();
System.out.println(getClass().getName());
}
}
测试类Test01
package fanxing;
//泛型测试
public class Test01 {
//泛型通配符测试方法
public static void take(Fanxing<?> f1){
f1.print();
}
public static void main(String[] args) {
Fanxing<Dog> fd1 = new Fanxing<Dog>(new Dog("你是狗吗?"));
Fanxing<Cat> fc1 = new Fanxing<Cat>(new Cat("你是猫吗?"));
Dog d1 = fd1.getT();
Cat c1 = fc1.getT();
d1.say();
c1.say();
take(fd1);
take(fc1);
}
}
输出结果
总结
1.泛型类的实例域为其他类对象
2.super
关键字代替有参方法时,super()
内加参数
3.泛型类声明时,只有类名后加<T>
4.泛型通配符为?
5.泛型类实例化时,需要加<T>
T为实际类型