zoukankan      html  css  js  c++  java
  • Java继承类中static成员函数的重写

    在java中,static成员函数是否可以被重写呢?

    结论是,你可以在子类中重写一个static函数,但是这个函数并不能像正常的非static函数那样运行。

    也就是说,虽然你可以定义一个重写函数,但是该函数没有多态特性。让我们测试一下:

    复制代码
     1 class  testClass1{
     2     static void SMothod(){
     3         System.out.println("static in testClass1");
     4     }
     5 }
     6 class testClass2 extends testClass1{
     7     static void SMothod(){
     8         System.out.println("static in testClass2");
     9     }
    10 }
    11 public class MainClass{
    12     public static void main(String... args){
    13         testClass1 tc1=new testClass2();
    14         testClass2 tc2 =new testClass2();
    15         tc1.SMothod(); //输出结果为 static in testClass1
    16         tc2.SMothod(); //输出结果为 static in testClass2
    17     }
    18 }
    复制代码

    从结果中可以看到,当我们用父类的实例引用(实际上该实例是一个子类)调用static函数时,调用的是父类的static函数。

    原因在于方法被加载的顺序。

    当一个方法被调用时,JVM首先检查其是不是类方法。如果是,则直接从调用该方法引用变量所属类中找到该方法并执行,而不再确定它是否被重写(覆盖)。如果不是,才会去进行其它操作(例如动态方法查询),具体请参考:方法的加载

  • 相关阅读:
    解决无法安装Microsoft .Net Framework 3.5
    day11-15,装饰器
    Xmanager Power Suit 6.0.0009 最新版注册激活
    eth
    MySql 8.0 版本使用navicat连不上解决
    day11
    Mybatis使用规则
    nginx的基本配置
    Mybatis分页插件PageHelper使用
    dubbo的使用
  • 原文地址:https://www.cnblogs.com/s844876674/p/4684477.html
Copyright © 2011-2022 走看看