码迷,mamicode.com
首页 > 编程语言 > 详细

java===java基础学习(11)---继承

时间:2018-04-08 16:06:12      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:格式   --   employee   类构造   pack   关键字   extends   构造   set   

下面是由继承Employee 类来定义Manager 类的格式, 关键字extends 表示继承。

public class Manager extends Employee

{

  添加方法和域

}

子类中继承父类的域和方法;

 

覆盖方法

父类的方法,并不适用于子类的时候,需要提供一个新的方法来覆盖父类中的这个方法

public double getSalary()

{

  double baseSalary = super.getSalary();

  return baseSalary + bonus;

}

 

子类构造器

public Manger(String name, double salary, int year, int month, int day)

{

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

  bonus = 0;

}

因为子类终的构造器不能直接访问父类的私有域,所以必须利用父类的构造器对这部分私有域进行初始化,可以使用super实现对父类构造器的调用。使用super调用构造器的语句必须是子类构造器的第一条语句。

package testbotoo;

import java.time.LocalDate;




public class Employee
{
    private String name;
    private double salary;
    private LocalDate 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 String getName()
    {
        return name;
    }
    
    public double getSalary()
    {
        return salary;
    }
    
}

 

package testbotoo;

public class Manager extends Employee 
{
    private double bonus;
    
    /**
     * @param name the employee‘s name
     * @param salary the salary
     * @param year the hire year
     * @param month the dire onth 
     * @param day the hire day 
     */
    
    public Manager(String name, double salary, int year, int month, int day)
    {
        super(name, salary, year, month, day);
        bonus = 0;
    }
    
    public double getSalary()
    {
        double baseSalary = super.getSalary();
        return baseSalary +bonus;
    }
    
    public void setBonus(double b)
    {
        bonus = b;
    }

}

 

package testbotoo;

public class ManagerTest {
    public static void main(String[] args)
    {
        Manager boss = new Manager("aaa",8000,1999,12,20);
        
        boss.setBonus(5000);
        
        Employee[] staff = new Employee[3];
        
        staff[0] = boss;
        staff[1] = new Employee("hary",5000,1989,3,15);
        staff[2] = new Employee("mayun",50000,1989,3,16);
        
        for (Employee e : staff)
            System.out.println("name="+e.getName()+",salary="+e.getSalary());
    }

}

 

java===java基础学习(11)---继承

标签:格式   --   employee   类构造   pack   关键字   extends   构造   set   

原文地址:https://www.cnblogs.com/botoo/p/8744893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!