zoukankan      html  css  js  c++  java
  • 使用super调用被子类覆盖的父类方法

    1.没有super方法

    /*
     * 子类方法覆盖父类方法,用super方法可以调用父类被覆盖的方法
     */
    
    class fruit{
        public fruit() {
            System.out.println("fruit !");
        }
        public void name() {
            System.out.println("我是水果!");
        }
    }
    
    class apple extends fruit{
        public apple() {
            System.out.println("apple !");
        }
        
        public void name() {
            //super.name();
            System.out.println("我是苹果!");
        }
    }
    
    
    public class fugai {
    
        public static void main(String[] args) {
            apple a=new apple();
            a.name();
        }
        
    }

    运行结果:

    fruit !
    apple !
    我是苹果!

    2.有super调用父类方法

     1 class fruit{
     2     public fruit() {
     3         System.out.println("fruit !");
     4     }
     5     public void name() {
     6         System.out.println("我是水果!");
     7     }
     8 }
     9 
    10 class apple extends fruit{
    11     public apple() {
    12         System.out.println("apple !");
    13     }
    14     
    15     public void name() {
    16         super.name();  //调用父类被覆盖方法
    17         System.out.println("我是苹果!");
    18     }
    19 }
    20 
    21 
    22 public class fugai {
    23 
    24     public static void main(String[] args) {
    25         apple a=new apple();
    26         a.name();
    27     }
    28     
    29 }

    运行结果如下:

    fruit !
    apple !
    我是水果!
    我是苹果!

    父类的方法被调用

    覆盖的规则

    1.覆盖方法的允许范围不能小于原方法

    2.覆盖方法所抛出的异常不能比原方法更多

    3.声明为final方法不允许覆盖

    4不能覆盖静态方法

  • 相关阅读:
    Redmine:数据库的账号密码配置
    EF:自定义Oracle的映射类型
    WCF:调用超时
    ibator使用心得
    Mantis部署步骤
    Detach之后的POCO如何Attach以及LoadProperty
    快速迭代与原型开发
    .net framework 4.0无法在Win7下安装的解决办法
    MVC和MVP的一些思考
    从类模型转换到数据库表结构的思考
  • 原文地址:https://www.cnblogs.com/cxy0210/p/11728600.html
Copyright © 2011-2022 走看看