Java中的静态方法能否被重写?

 

*非静态方法属于类的实例,是可以被子类重写,从而达到多态的效果; 
 静态方法属于类,是不能被重写,故而也不能实现多态。*

下面是具体的验证过程

首先,定义一个超类A,里边定义一个静态方法和一个非静态方法:

publicclass A {    publicvoidunstaticMethod() {        System.out.println("SuperClass unstaticMethod");    }    publicstaticvoidstaticMethod() {        System.out.println("SuperClass staticMethod");    }}
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

接下来,定义一个子类B,里边定义一个静态方法和一个非静态方法(形式上像是重写了超类的方法):

publicclassBextendsA {publicvoidunstaticMethod() {        System.out.println("SunClass unstaticMethod");    }    publicstaticvoidstaticMethod() {        System.out.println("SunClass staticMethod");    }}
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

在接下来,我们进行测试

publicclass Test {    @SuppressWarnings("static-access")    publicstaticvoidmain(String[] args) {        A a = new A();        A a2 = new B();        a.unstaticMethod();        a2.unstaticMethod();        a.staticMethod();        a2.staticMethod();    }}
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

运行结果:

SuperClass unstaticMethodSunClass unstaticMethodSuperClass staticMethodSuperClass staticMethod
  • 1

  • 2

  • 3

  • 4

  • 5

  • 1

  • 2

  • 3

  • 4

  • 5

从运行结果,我们可以知道,对于非静态方法,实现了多态的效果,而静态方法却没有。

 

50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信