狗跳高案例和学生老师案例(继承,抽象类,接口)

博客围绕狗跳高和学生老师两个案例展开,介绍从抽象到具体的实现过程,强调接口比抽象类更抽象,先编写接口,再编写抽象类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

狗跳高案例 

从抽象到具体一一实现
        接口比抽象类更抽象,先写接口
        然后抽象类

//扩展功能用接口
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();
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值