Java基础_09 | 子类中对父类已有方法的重写(重写的语法规则、重写与重载的区别、重写的示例程序)

1.重写的语法规则

1.1.为什么需要重写

一个子类在继承父类方法的时候,如果继承的父类方法不能满足新的要求,这个时候就需要对父类的方法进行重写,重新设计该方法。

1.2.重写的语法规则

  • 方法名要相同;
  • 参数列表要相同;
  • 返回值类型要相同;
  • 访问权限只能同级或者扩大,不能缩小;

1.3.重写与重载的区别

  • 重写是指子类对继承的父类已有方法的重新设计
  • 重载是指在一个类中,可以出现多个同名方法,但是参数列表不同,返回值无要求,称为该方法的重载;

2.重写的示例程序

/**
 * @brief   子类重写父类方法示例程序
 * @author  mculover666
 * @date    2019/4/28
 */
class People
{
    /* 属性需要被继承的子类使用,所以修饰为protected */
    protected String name;
    protected String sex;
    protected int age;

    public People()
    {

    }
    public People(String name, String sex,int age)
    {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    /**
     * 获取信息
     */
    public String getInfo()
    {
        String info = name +'\t'+ sex +'\t'+ age;
        return info;
    }
}
class Student extends People
{
    int score;

    public Student()
    {

    }
    public Student(String name, String sex,int age,int score)
    {
        super(name, sex, age);
        this.score = score;
    }
    /**
     * 对父类获取信息的方法进行重写
     */
    public String getInfo()
    {
        String info = super.getInfo() + '\t' + age;
        return info;
    }
}
class TestOver
{
    public static void main(String[] args) 
    {
        Student student1 = new Student("mculover666", "男", 21 , 99);
        System.out.println(student1.getInfo());
    }
}

测试结果如下:

接收更多精彩文章及资源推送,欢迎订阅我的微信公众号:『mculover666』

发布了208 篇原创文章 · 获赞 559 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/Mculover666/article/details/89638373