狗跳高案例
从抽象到具体一一实现
接口比抽象类更抽象,先写接口
然后抽象类
//扩展功能用接口
interface Jump{
public abstract void jump();
}
abstract class Animal2{
//成员变量
private String name;
private int age;
//构造方法
public Animal2() {}
public Animal2(String name,int age) {
this.name = name;
this.age = age;
}
//get/set
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 abstract void eat();
//睡觉都一样
public void sleep() {}
}
class DogA extends Animal2{
//构造方法
public DogA() {}
public DogA(String name,int age) {
super(name,age);//调用父类构造方法
}
public void eat() {
System.out.println("狗吃肉");
}
public void sleep() {
System.out.println("狗睡觉");
}
}
class JumpDog extends DogA implements Jump{
public JumpDog() {}
public JumpDog(String name,int age) {
super(name,age);
}
public void jump() {
System.out.println("跳高狗");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
JumpDog jd = new JumpDog();
jd.setName("Tom");
jd.setAge(10);
System.out.println(jd.getName()+"---"+jd.getAge());
jd.eat();
jd.sleep();
jd.jump();
}
}
学生老师案例
interface Yan{
public void chouyan();
}
abstract class Person{
private String name;
private int age;
public Person() {}
public Person(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 abstract void eat();
public void sleep() {}
}
class Student extends Person{
public Student() {}
public Student(String name,int age) {
super(name,age);
}
public void eat() {
System.out.println("学生吃饭");
}
public void sleep() {
System.out.println("学生睡觉");
}
}
class Teacher extends Person{
public Teacher() {}
public Teacher(String name,int age) {
super(name,age);
}
public void eat() {
System.out.println("老师吃饭");
}
public void sleep() {
System.out.println("老师睡觉");
}
}
class TeacherChouYan extends Teacher implements Yan{
public void chouyan() {
System.out.println("老师抽烟");
}
}
public class StudentTeacher {
public static void main(String[] args) {
// TODO Auto-generated method stub
TeacherChouYan y = new TeacherChouYan();
y.setName("鲁班");
y.setAge(20);
System.out.println(y.getAge()+"--"+y.getName());
y.chouyan();
y.eat();
y.sleep();
}
}