(OJ)Java面向对象-面向对象综合题2

面向对象综合题2

Problem Description

要求如下:
1.定义一个抽象的"Role"类,有姓名、年龄、性别等成员变量。要求尽可能隐藏所有变量(能够私有就私有,能够保护就不要公有) 。具有一个抽象的play()方法,该方法不返回任何值,同时至少定义两个构造方法。
2. 从Role类派生出一个"Employee"类 该类具有Role类的所有成员,并扩展 salary成员变量,同时增加一个静态成员变量职工编号"id"。同样要有至少两个构造方法,要体现出this和super的几种用法,还要求覆盖play()方法,并提供一个final sing()方法。 
3. "Manager"类继承"Employee"类,有一个final成员变量"vehicle" 。
4. 在Main类中产生Manager和Employee对象,并测试这些对象的方法。

代码如下:

class Employee extends Role1
{
    protected int id;
    protected int salary;
    public Employee(){}
    public Employee(String name,int age,String sex,int id,int salary)
// 你的代码将被嵌入这里

class Main{
    public static void main(String[] dsa)
    {
         Employee e=new Employee("you xiao",20,"Man",1201012204,15000);
         Manager m=new Manager();
         System.out.println(e.id);
         System.out.println(e.salary);
         System.out.println(e.name);
         System.out.println(e.age);
         System.out.println(e.sex);
         System.out.println(m.vehicle);
         m.play();
         m.sing();
    }
}

Output Description

1201012204
15000
you xiao
20
Man
Lamborghini
i can paly
i can sing

解题代码

// 补全Employee类
	// 构造方法
	{
    
    
        // 调用父类的带三个参数的构造方法
        super(name,age,sex);
        this.id = id;
        this.salary = salary;
    }

	// 重写父类的play方法
    @Override
    public void play() {
    
    
        System.out.println("i can paly");
    }

	// sing方法
    public final void sing() {
    
    
        System.out.println("i can sing");
    }
}
// 抽象类Role1
abstract class Role1 {
    
    
    // 受保护的name 属性
    protected String name;
	// 受保护的age 属性
    protected int age;
	// 受保护的sex 属性
    protected String sex;
	// 无参构造
    public Role1() {
    
    
    }
	// 带参构造
    public Role1(String name, int age, String sex) {
    
    
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
	// 抽象方法play
    public abstract void play();
}
// Manager类继承Employee类
class Manager extends Employee {
    
    
    // 常量vehicle 常量名应该大写
    public final String vehicle = "Lamborghini";
	// 无参构造
    public Manager(){
    
    
        // 调用父类的无参构造 默认会调用
        super();
    }
	// 带参构造
    public Manager(String name, int age, String sex, int id, int salary) {
    
    
        // 调用父类的带参构造
        super(name,age,sex,id,salary);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40856560/article/details/112564081
今日推荐