类的设计应该保证父类和子类能够共享特征。有时将一个父类设计的非常抽象,以至于它没有
具体的实例,这样的就可以声明为抽象类。
用abstract关键字修饰一个类,这个类就是抽象类
用abstract来修饰一个方法时,这个方法就是抽象方法
抽象方法:只有方法声明,没有方法的实现以分号结束abstract int abstractMethod(int a);
含有抽象方法的类必须被声明为抽象类抽象类是用来被继承的,抽象类的子类必须重写父类的抽象方法,并提供方法体。若没有重写全部的抽象方法,仍为抽象类。
不能用abstract修饰属性、私有方法、构造器、静态方法、final的方法。
抽象类不能被实例化。
public abstract class Pet {
private String name;
private int age;
private double weight;
public Pet(String name, int age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String toString() {
return "名字:"+name+",年龄:"+age+",重量:"+weight;
}
public abstract void speak();
public abstract void eat();
}
class PetT{
public static void main(String[] args) {
Pet p= new Pet("测试",20,50);//抽象类不可以new对象
}
}
一个继承抽象类父类的子类
public abstract class Pet {
private String name;
private int age;
private double weight;
public Pet(String name, int age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String toString() {
return "名字:"+name+",年龄:"+age+",重量:"+weight;
}
public abstract void speak();
public abstract void eat();
}
class Bird extends Pet{
private int fly;
public Bird(String name, int age, double weight,int fly) {
super(name, age, weight);
this.fly = fly;
}
public int getFly() {
return fly;
}
public void setFly(int fly) {
this.fly = fly;
}
@Override
public void speak() {
System.out.println("genlonggenglong");
}
@Override
public void eat() {
System.out.println("chongzi");
}
@Override
public String toString() {
return super.toString()+",飞行:"+fly;
}
}
class Test{
public static void main(String[] args) {
Pet p = new Bird("测试",20,50,60);
p.eat();
p.speak();//虚方法调用
System.out.println(p);
}
}
抽象类中可以包括:
属性 构造器 具体方法 抽象方法