员工类继承java_38.Java继承经典案列-经理与员工(2.0)

已知employee员工是超类,manager经理是子类

manager—>employee

set方法给属性赋值,get方法取得值

1、超类Employee.java

定义属性private私有—》构造方法初始化对象—》用get方法取得值—》LocalDate在JDK1.8中,新增了处理日期的类

LocalDate.of(int year, int month, int dayOfMonth)

根据参数设置日期,参数分别为年,月,日

package com.em;

//import java.util.Date;

import java.time.LocalDate;

public class Emlpoyee {

private String name;

private double salary;

private LocalDate dateday;

public Emlpoyee(String namae,double salary,int year,int month,int day){

this.name = namae;

this.salary = salary;

// this.dateday = dateday;

dateday = LocalDate.of(year,month,day);

}

public String getName() {

return name;

}

public double getSalary() {

return salary;

}

public LocalDate getDateday() {

return dateday;

}

}

2、子类Manager.java

定义属性private私有—》构造方法初始化对象—》set方法赋值属性extra—》get方法获取超类的getSalary(),这里不能直接返回想要的值 return salary2 + extra; 这会报错的 —原因是 我文章36.继承私有域的理解

—》解决 借助接口 + super

所以是 double salary2 = super.getSalary();

return salary2 + extra;

package com.em;

//import java.util.Date;

public class Manager extends Emlpoyee{

private double extra;

public Manager(String namae,double salary,int year,int month,int day){

super(namae,salary,year,month,day);

// super(namae, salary, dateday);

extra = 0; //默认值

}

public double getSalary() {

// double salary2 = getSalary();//不能

double salary2 = super.getSalary();

return salary2 + extra;

}

public void setExtra(double extra) {

this.extra = extra;

}

}

3、测试类 Test.java

用子类Manager创建对象(new)并赋值—》该对象调用Manager里面赋好值的set方法—》用超类Employee创建对象(new)并赋值,第一个由于后面要循环遍历出来,用上面那个Manger创建好的值—》for(Employee e : staff)把数组循环遍历出来—》sout+e.get方法

另一种方式遍历

for (int i = 0; i < arr.length; i++){

System.out.println(arr[i]);

}

package com.em;

public class Test {

public static void main(String[] args) {

Manager mange = new Manager("xiaoming",80000,2020,1,2);

mange.setExtra(19999);

Emlpoyee[] emlpoyees = new Emlpoyee[3];

emlpoyees[0] = mange;

emlpoyees[1] = new Emlpoyee("xiaozhang",80000,2020,1,3);

emlpoyees[2] = new Emlpoyee("xiaohua",60000,2020,1,3);

for (Emlpoyee e : emlpoyees){

System.out.println("name=" + e.getName() +",salary=" + e.getSalary() + ",date=" + e.getDateday());

}

}

}

4、运行结果:

name=xiaoming,salary=99999.0,date=2020-01-02

name=xiaozhang,salary=80000.0,date=2020-01-03

name=xiaohua,salary=60000.0,date=2020-01-03

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值