Java工厂模式的技术核心

首先通过代码来分析一下:

先定义一个Employee的超类,然后定义一个Manager类型的子类,继承于该超类,代码如下:

public class Employee {

	private String name;
	private double salary;
	private LocalDate hireDay;	
	Employee(){}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public LocalDate getHireDay() {
		return hireDay;
	}
	public void setHireDay(LocalDate hireDay) {
		this.hireDay = hireDay;
	}
	public Employee(String name, double salary ,int year,int month,int day) {
		
		this.name = name ;
		this.salary = salary;
		hireDay = LocalDate.of(year, month, day);
	}
public class Manager extends Employee{
	
	private double bouns;
	public Manager(String name, double salary, int year, int month, int day) {
		super(name, salary, year, month, day);
		bouns = 0;
	}
    public double getSalary() {
    	double baseSalary = super.getSalary();
    	return baseSalary + bouns;
    }
	public void setBonus(double b) {
		bouns = b;
	}
	

}
public class ManagetText {

	public static void main(String[] args) {
		
		Manager boss = new Manager("aaa",8000,1999, 9,2);
		boss.setBonus(200);
		Employee [] staff = new Employee[3];
		staff[0] = boss;
		staff[1] = new Employee("sdsa", 3000, 2000, 2, 2);
		staff[2] = new Employee("sdsa", 3000, 2000, 2, 2);
		
		for( Employee s :staff  ) {
			System.out.println(s.getName()+"  "+ s.getSalary());
		}
	}

}
结果:
aaa  8200.0
sdsa  3000.0
sdsa  3000.0

将子类对象赋值给超类对象时,超类对象仅仅接受自己所包含的成员变量的值或成员方法。就比如上面的例子中,staff[0] = boss; 但是staff[0]声明的是Employee类型的,它不能访问Manager类型对象所独有的方法,比如说setBouns()方法,staff[0]是没有访问权限的。这造成了对象数据的丢失。

但是如果将staff声明成Manager类型,这样就可以避免数据的损失。

这种问题在类的继承中 比较常见,并且在之后的工厂方法中也是非常重要的技术要点!!!

 

参考;《java核心技术卷一》

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值