【Java题】实现继承和多态的例子
一:题目
1.员工类Employee:
(1)私有成员变量:姓名,年龄,工资
(2)提供无参,有参构造
(3)成员方法:work()方法——员工工作
2.程序员类Coder:
(1)继承Employee父类
(2)提供无参,有参构造
(3)成员方法:重写work()方法——姓名为张三,年龄为22,工资为15000的程序员正在编写代码
(4)自己独有的方法——发疯
3.测试类Test
二:提示
1.super://调用父类的构造方法
2.重写:子类根据需要实现父类的方法
三:代码
Employee.java
public class Employee {
private String name;
private int age;
private double salary;
protected Employee(){}
protected Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public void work(){
System.out.println("员工工作");
}
}
Coder.java
public class Coder extends Employee {
public Coder(){
}
public Coder(String name,int age,double salary){
super(name, age, salary);//调用父类的构造方法
}
//重写work方法
@Override
public void work() {
System.out.println(String.format("姓名为%s,年龄为%d,工资为%f的员工正在编写代码",
getName(),getAge(),getSalary()));
}
public void crazy(){
System.out.println(String.format("%s已经疯了",getName()));
}
}
Test.java
public class Test {
public static void main(String[] args) {
Employee c = new Coder("小李",25, 7500);//向上转型
work(c);
special(c);
}
public static void work(Employee e){
e.work();//运行时多态
}
public static void special(Employee e){
if(e instanceof Coder){
Coder coder=(Coder)e;//向下转型
coder.crazy();
}
}
}