首页 > 代码库 > 抽象类的练习
抽象类的练习
package lianxi4;public abstract class Employee { private String name; private int number; private MyDate birthday;public String getName() { return name;}public void setName(String name) { this.name = name;}public int getNumber() { return number;}public void setNumber(int number) { this.number = number;}public MyDate getBirthday() { return birthday;}public void setBirthday(MyDate birthday) { this.birthday = birthday;}public Employee(String name, int number, MyDate birthday) { super(); this.name = name; this.number = number; this.birthday = birthday;}public abstract double earnings();@Overridepublic String toString() { return "birthday=" + birthday.toDateString() + ", name=" + name + ", number=" + number + "]";}}
package lianxi4;public class MyDate { private int month; private int day; private int year;public MyDate(int month, int day, int year) { super(); this.month = month; this.day = day; this.year = year;}public int getMonth() { return month;}public void setMonth(int month) { this.month = month;}public int getDay() { return day;}public void setDay(int day) { this.day = day;}public int getYear() { return year;}public void setYear(int year) { this.year = year;}public String toDateString(){ return this.year+"年"+this.month+"月"+this.day+"日";}}
package lianxi4;public class SalariedEmployee extends Employee{private double monthlySalary;public SalariedEmployee(String name, int number, MyDate birthday,double monthlySalary){ super(name,number,birthday); this.monthlySalary = monthlySalary;}@Overridepublic double earnings() { return monthlySalary;}@Overridepublic String toString() { return "SalariedEmployee ["+super.toString()+"monthlySalary=" + monthlySalary + "]";}}
package lianxi4;import java.util.Scanner;public class PayrollSystem { public static void main(String[] args) { Employee []emps = new Employee[2]; //注意,虽然Employee是抽象类,但是是定义数组,不是实例化 emps[0] = new SalariedEmployee("小明",1001,new MyDate(5,3,1990),4000);//体现多态性 emps[1] = new HourlyEmployee("小红",1002,new MyDate(4,12,1993),20,8); Scanner s = new Scanner(System.in); System.out.println("请输入当前月份"); int month = s.nextInt(); for(int i=0;i< emps.length;i++){ System.out.println(emps[i]); if(month==emps[i].getBirthday().getMonth()){ System.out.println("增加"+emps[i].getName()+"工资100元"); } } }}
结果:
请输入当前月份
4
SalariedEmployee [birthday=1990年5月3日, name=小明, number=1001]monthlySalary=4000.0]
HourlyEmployee [birthday=1993年4月12日, name=小红, number=1002]hour=8, wage=20.0]
增加小红工资100元
抽象类的练习
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。