Java-11 方法覆盖

方法覆盖(override) | 重写(rewrite):
    条件:
        1.必须基于继承关系
        2.子类对父类的方法进行重构,当子类调用重写方法时,执行的方法为自身重写过的方法

注意:
    1.方法名称一致
    2.参数列表一致(参数类型一致,参数个数一致,参数顺序一致)
    3.返回值类型一致
    4.子类访问权限>=父类访问权限

方法重载(overload):
    条件:基于当前类

    作用:通过同一方法名,传入不同的参数,实现相同的功能

    注意:
    1.方法名一致
    2.参数列表不一致(参数类型不一致、参数个数不一致、参数顺序不一致)
    3.返回值可以一致,可以不一致


public class Employee {

String name;
String birth;
double salary;

//构造函数
public Employee()
{
    System.out.println("new Employee()实例化---父类");
}
public Employee(String name,String birth,double salary)
{
    this.name = name;
    this.birth = birth;
    this.salary = salary;
}

public void getDetail()
{
    System.out.println("name:" + name +"\t birth:" +birth+"\t salary:" + salary);
}

public double getSalary()
{
    return salary;
}
}

覆盖父类的方法:

public class Worker extends Employee{

String sex;

public Worker()
{
    super();
}

public Worker(String name,String birth,double salary,String sex)
{
    super(name,birth,salary);
    this.sex = sex;
}

public void dressAllowance()
{
    System.out.println("Worker.dressAllowance:" + 500);
}

@Override //覆盖、重写
public void getDetail() {
    System.out.println("name:" + name +"\t birth:" +birth+"\t salary:" + salary+"\t sex:" + sex);
}
}

测试:

public static void main(String[] args) {
    Worker worker = new Worker("李四","2018-8-9",5000.0,"男");
    worker.getDetail();//调用覆盖之后的方法
}

猜你喜欢

转载自blog.csdn.net/qq_36090002/article/details/81604505
今日推荐