zoukankan      html  css  js  c++  java
  • java之方法的重写

    在子类中可以根据需要对从父类中继承而来的方法进行改造,也称为重写。在执行程序时,子类的方法将覆盖父类的方法。

    要求:

    • 重写方法必须和被重写的方法的具有相同的方法名称、参数列表和返回值类型;
    • 重写方法不能使用比被重写方法更严格的访问权限;
    • 重写和被重写的方法需同时为static的,或同时为非static的;
    • 子类方法抛出的异常不能大于父类被重写方法的异常;

    举个例子:
    Person.java

    package myjava;
    
    public class Person {
        private String name;
        private int age;
    
        public void setName(String name) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public int getAge() {
            return this.age;
        }
        
        public void show() {
            System.out.println("hello person");
        }
    }

    Student.java

    package myjava;
    
    public class Student extends Person{
        
        public void show() {
            System.out.println("hello student");
        }
        
    }

    Test.java

    package myjava;
    
    public class Test {
        public static void main(String[] args) {
            
            Person p = new Person();
            Student stu = new Student();
            p.show();
            stu.show();
    }

    输出结果:
    hello person

    hello student

    可以看到,虽然Peroson类中和Student类中都存在相同的show()方法,但是里面的内容确是不一样的,在调用的时候是分别调用自己类中的方法,如果在Student类中不进行产重写show()方法,那么,最后的结果就是:

    hello person

    hello person

    也就是都会调用父类的方法。

  • 相关阅读:
    券商
    养生之道
    房产买卖
    货币常识
    虚拟币
    其他开源项目
    Shiro
    文件上传插件
    JAVA常见问题
    如何写好PPT
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12045544.html
Copyright © 2011-2022 走看看