• 子类重写父类的方法应注意的问题


    若想实现一个合格重写方法,而不是重载,那么必须同时满足下面的要求!

    重写规则之一:重写方法不能比被重写方法限制有更严格的访问级别。
    (但是可以更广泛,比如父类方法是包访问权限,子类的重写方法是public访问权限。) 比如:Object类有个toString()方法,开始重写这个方法的时候我们总容易忘记public修饰符,编译器当然不会放过任何教训我们 的机会。出错的原因就是:没有加任何访问修饰符的方法具有包访问权限,包访问权限比public当然要严格了,所以编译器会报错的。

    重写规则之二: 参数列表必须与被重写方法的相同。
    重写有个孪生的弟弟叫重载,也就是后面要出场的。如果子类方法的参数与父类对应的方法不同,那么就是你认错人了,那是重载,不是重写。

    重写规则之三:返回类型必须与被重写方法的返回类型相同。
    父类方法A:void eat(){} 子类方法B:int eat(){} 两者虽然参数相同,可是返回类型不同,所以不是重写。
    父类方法A:int eat(){} 子类方法B:long eat(){} 返回类型虽然兼容父类,但是不同就是不同,所以不是重写。

    重写规则之四:重写方法不能抛出新的异常或者比被重写方法声明的检查异常更广的检查异常。但是可以抛出更少,更有限或者不抛出异常。
    注意:这种限制只是针对检查异常,至于运行时异常RuntimeException及其子类不再这个限制之中。

    重写规则之五: 不能重写被标识为final的方法。

    重写规则之六:如果一个方法不能被继承,则不能重写它。如private方法
    比较典型的就是父类的private方法。下例会产生一个有趣的现象。
    public class Test {
      public static void main (String[] args) {
       //Animal h = new Horse();
       Horse h = new Horse();
        h.eat();
       }
    }

    class Animal {
       private void eat(){
        System.out.println ("Animal is eating.");
        }
     }

    class Horse extends Animal{
       public void eat(){
         System.out.println ("Horse is eating.");
       }
    }
    这段代码是能通过编译的。表面上看来违反了第六条规则,但实际上那是一点巧合。Animal类的eat()方法不能被继承,因此Horse类中的 eat()方法是一个全新的方法,不是重写也不是重载,只是一个只属于Horse类的全新的方法!这点让很多人迷惑了,但是也不是那么难以理解。
    main()方法如果是这样:
    Animal h = new Horse();
    //Horse h = new Horse();
    h.eat();
    编译器会报错,为什么呢?Horse类的eat()方法是public的啊!应该可以调用啊!请牢记,多态只看父类引用的方法,而不看子类对象的方法!

    重写规则之七:子类不能用 静态方法 重写 父类的非静态方法

    编绎无法通过this static method cannot hide the instance mehtod from


    class A {
      protected  int method1(int a, int b) {
      return 0;
     }
    }

    public class Test1 extends A {

     private int method1(int a, long b) {
      return 0;
     }
    //this static method cannot hide the instance mehtod from A
       static public int method1(int a, int b) {
      return 0;
     }
    }

    重写规则之八:子类不能用 非静态方法 重写 父类的静态方法

    编绎报错:this instance method cannot override the static mehtod from A
    class A {
      protected  static int method1(int a, int b) {
      return 0;
     }
    }

    public class Test1 extends A {

     private int method1(int a, long b) {
      return 0;
     }
    //this static method cannot hide the instance mehtod from A
     //this instance method cannot override the static mehtod from A
        public int method1(int a, int b) {
      return 0;
     }
    }

  • 相关阅读:
    git处理冲突提交,撤销提交命令
    RocketMQ(4.7.0)单机与集群搭建,控制台搭建,并与springboot整合
    JVM进程的优雅关闭
    MySQL字段等值查询时,尾部有空格也能匹配上的坑
    带有连接池的Http客户端工具类HttpClientUtil
    比较两个jar包的版本号
    源码解读SLF4J绑定日志实现的原理
    log4j输出到控制台的性能问题
    多表查询
    分页优化
  • 原文地址:https://www.cnblogs.com/canceler/p/4605394.html
Copyright © 2020-2023  润新知