Java实验2:继承、接口与多态

该实验涉及Java编程,创建了People父类和Employee子类。Employee类继承了People类的属性(姓名、性别、年龄)并添加了工号和工作方法。实验通过创建Employee和People对象,展示了类的继承特性和方法的覆盖。
摘要由CSDN通过智能技术生成
【实验内容 1】
创建父类、子类实现继承
【实验要求】
编程实现类的继承。编写父类People,子类Employee继承自人类。人类具有姓名,性别,年龄
等性质,还具有吃和说的行为。雇员类继承父类,还拥有工号性质和工作行为。构造人类和学生类
的对象,调用吃、说、工作的方法输出有关信息。
【实验代码】
1.People类
public class People {
	
	protected String name;//姓名
	protected String gender;//性别
	protected int age;//年龄
	
	public void eat() {//吃
		System.out.println("我是人,我爱吃饭! ");
	}
	public void speak() {//说话
		System.out.println("我是人, 我爱说话!");
	}
	
	public String getName(){
		return this.name;
	}
	public String getGender(){
		return this.gender;
	}
	public int getAge(){
		return this.age;
	}
	
	public People(String name, String gender, int age) {//初始化共有属性
		this.name = name;
		this.gender = gender;
		this.age = age;
	}
}

2.Employee类

public class Employee extends People{
	private int id;//工号
	
	public Employee(String name, String gender, int age, int id) {//构造方法
		super(name, gender, age);//重定义父类成员变量
		this.id = id;
		}
	
	public int getId() {
		return this.id = id;
	}
	public void setId(int id) {
		this.id = id;
	}

	
	@Override
	public void eat() {
		System.out.println("我是员工,我爱吃饭");
	}
	@Override
	public void speak() {
		System.out.println("我是员工,我爱说话");
	}
	public void work() {
		System.out.println("我是员工,我的工作内容很简单!");
	}
}

3.Test04类(运行该类即可)

public class Test04 {
	public static void main(String[] args) {
		Employee employee = new Employee("张三","男",18,13000000);
		
		System.out.println("这是一名员工:");
		System.out.println("姓名:"+employee.getName());
		System.out.println("性别:"+employee.getGender());
		System.out.println("年龄:"+employee.getAge());
		System.out.println("工号:"+employee.getId());
		employee.eat();
		employee.speak();
		employee.work();
		System.out.println();
		
		
		People people = new People("丽丝","女",16);
		System.out.println("这是一个普通的人:");
		System.out.println("姓名:"+people.getName());
		System.out.println("性别:"+people.getGender());
		System.out.println("年龄:"+people.getAge());
		people.eat();
		people.speak();
	}
}

【实验结果】

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值