面向对象三大特性【继承】

继承
a.概念:继承是面向对象最为显著的一个特性。继承是从已有的类中派生出新的类,新的类能够刺手已有类的数据属性和行为,并能扩展新的能力。类的继承性主要表现为子类继承父类相关的数据成员和成员方法
b.用途:扩展(增加属性 方法)
继承实例
需求:
项目经理类
属性:姓名 工号 工资 奖金
行为:工作work(打印姓名、工号、工资、奖金)
程序员类
属性:姓名 工号 工资
行为:工作work(打印姓名、工号、工资)
分析:
显然程序员类与项目经理类有相同属性(姓名、工号、工资),但是项目经理明显比程序员类多了一个奖金的属性,此时我们就可以用继承的思想设计程序员类和经理类,要求类中提供必要的方法进行属性访问,至于行为,有奖金就输出奖金,没有就不输出。

public class Programer {
//Programer类中的成员变量
	private String name;
	private int id;
	private int money;

	public Programer(String name, int id, int money) {
		this.name = name;
		this.id = id;
		this.money = money;

	}
	public void work() {
		// 工作work(打印姓名、工号、工资)

		System.out.println(this.name + " " + "工号:" + this.id + "工资" + this.money);
	}
}
public class Manager extends Programer {

	public Manager(String name, int id, int money) {
		super(name, id, money);
	}

	private int bonus;

	public void setBonus(int bonus) {
		this.bonus = bonus;
	}

	public void work() {
		super.work();//访问父类中的work
		System.out.println("经理:");
		System.out.println(" " + "奖金:" + this.bonus);
	}
}
public class 测试 {

	public static void main(String[] args) {
			Manager t = new Manager("小王",4568,5000);
			t.setBonus(355);
			t.work();
//			t.setBonus(355);
			Programer t1= new Programer("张三",489546,6000);
			t1.work();
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_44084434/article/details/90107414