抽象类和抽象方法的注意事项:
抽象类不能实例化
抽象类中不一定有抽象方法,有抽象方法的类一定是抽象类可以有构造方法抽象类的子类
要么重写抽象类中的所有抽象方法要么是抽象类
练习:
编写带有抽象类的标准Javabean类
青蛙frog 属性:名字,年龄 行为:吃虫子,喝水
狗Dog 属性:名字,年龄 行为:吃骨头,喝水
山羊Sheep 属性:名字,年龄 行为:吃艹,喝水
分析:
将此三类的共性抽取到父类Animal,因为这三类里吃东西的行为不同,所以将此行为化为抽象方法,Animal为抽象类
Animal:
public abstract class Animal { //父类,抽象类
private String name;
private int age;
public Animal() {
}
public Animal(String name,int age) {
this.name=name;
this.age=age;
}
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 void drink() {
System.out.println("动物在喝水");
}
public abstract void eat();//抽象类
}
Frog:
public class Frog extends Animal{ //青蛙
public Frog() {
}
public Frog(String name,int age) {
super(name,age);
}
public void eat() {
System.out.println("青蛙吃虫子");
}
}
Dog:
public class Dog extends Animal{ //狗
public Dog() {
}
public Dog(String name,int age) {
super(name,age);
}
@Override
public void eat() {
System.out.println("狗吃骨头");
}
}
Sleep:
public class Sleep extends Animal{ //山羊
public Sleep() {
}
public Sleep(String name,int age) {
super(name,age);
}
public void eat() {
System.out.println("山羊吃草");
}
}
测试类:
package test02;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Frog f=new Frog("小绿",3);
System.out.println(f.getName()+","+f.getAge());
f.drink();
f.eat();
}
}
运行结果: