1.抽象类:里面有抽象方法时,就要声明该类为抽象类
public abstract class Animal {private String name;private int age;public Animal() {}public Animal(String name, int age) {this.name = name;this.age = age;}/*** 获取* @return name*/public String getName() {return name;}/*** 设置* @param name*/public void setName(String name) {this.name = name;}/*** 获取* @return age*/public int getAge() {return age;}/*** 设置* @param age*/public void setAge(int age) {this.age = age;}public String toString() {return "Animal{name = " + name + ", age = " + age + "}";}//抽象类,只能写在抽象方法中public abstract void eat();
}
2.接口类:行为方法
public interface Swim {public void swim();
}
3.其他类
继承,并且实现接口的函数
接口中的方法要实现就都得实现
public class Frog extends Animal implements Swim{public Frog() {}public Frog(String name, int age) {super(name, age);}@Overridepublic void eat(){System.out.println("青蛙吃虫子");}@Overridepublic void swim(){System.out.println("蛙泳");}}//可以继承父类也可以实现接口//填写构造方法//重写吃和游泳
兔子没有游泳这个行为,所以不用实现接口
public class Rabbit extends Animal {//要加上继承的关键字,接口要加上interface关键字public Rabbit() {}public Rabbit(String name, int age) {super(name, age);}@Overridepublic void eat() {System.out.println("Rabbit eat");}
}//添加构造方法,把父类的name和age也加过来//原来这就是重写的用法,用在抽象和接口中