抽象类,即类名前加上abstract。
注意事项:
1. 含有abstract方法的类必须声明为抽象类。抽象类必须被继承,抽象方法必须被重写。
2. 抽象类不能被实例化。
3.抽象方法只需声明,不用实现。(相当于C++的纯虚函数)
举例:
abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public abstract void voice();
public abstract void color();
}
class Cat extends Animal {
public String eyesColor;
Cat(String n, String c) {
super(n);
eyesColor = c;
}
public void voice() {
System.out.println("猫叫声:Miao~Miao~~");
}
public void color() {
System.out.println("颜色:" + eyesColor);
}
}
class Dog extends Animal {
String furColor;
Dog(String s, String c) {
super(s);
furColor = c;
}
public void voice() {
System.out.println("狗叫声:Wang~Wang~Wang~");
}
public void color() {
System.out.println("颜色:" + furColor);
}
}
class person {
private Animal pet;
public person(Animal animal) {
pet = animal;
}
public void petvoice() {
pet.voice();
}
public void petColor() {
pet.color();
}
}
public class tString {
public static void main(String[] args) {
Cat c2 = new Cat("Kitty", "Pink");
Dog d2 = new Dog("Snube", "White");
person p = new person(c2);
person p2 = new person(d2);
p.petvoice(); p.petColor();
p2.petvoice(); p2.petColor();
}
// 输出结果:
// 猫叫声:Miao~Miao~~
// 颜色:Pink
// 狗叫声:Wang~Wang~Wang~
// 颜色:White
}