Java中子类是否可以继承父类的static变量和方法而呈现多态特性

Java中子类是否可以继承父类的static变量和方法而呈现多态特性

静态方法

通常,在一个类中定义一个方法为static,那就是说,无需本类的对象即可调用此方法,关于static方法,声明为static的方法有以下几条限制:

  • 它们仅能调用其他的static 方法。
  • 它们只能访问static数据。
  • 它们不能以任何方式引用this 或super。

无论是static修饰的变量,还是static修饰的方法,我们都知道他们是属于类本身的,不是属于某一个对象的,当声明一个对象时,并不产生static变量和方法的拷贝。也就是说,用static修饰的变量和方法在类加载的时候,只分配一块存储空间,所有此类的对象都可以操控此块存储空间;

:这里要说明的时,当子类没有与之同名的static变量(或方法时),子类的对象也可以操控这块内存空间。但是子类并没有继承父类中static修饰的变量和方法。因为static修饰的变量和方法是属于父类本身的。

//————————以上我相信我们每个人都比较清楚。

但是,不知道你有没有注意到这种情况,当存在继承关系时,父类中有一个static修饰的变量(或方法),而子类中也存在一个同名的static修饰的变量(或方法)时,他们到底是否满足“重写”,而最终体现出多态的效果呢??

下面来看一个例子。 
父类中有一个static修饰的方法和一个普通的方法,子类中也有一个同名的static方法和一个普通的方法。如下

父类


public class Parent {
    public static void staticMethod(){ System.out.println("Parent staticMethod run"); } public void method(){ System.out.println("Parent method run"); } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

子类


public class Son extends Parent { public static void staticMethod(){ System.out.println("Son staticMethod run"); } public void method(){ System.out.println("Son method run"); } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

测试类

package com.wrh.teststaticmethod;

public class Test {

    public static void main(String[] args) { Parent child=new Son(); child.staticMethod();//输出:Parent staticMethod run Son s=new Son(); s.staticMethod(); child.method();//这样才存在多态 } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

运行后的结果如下:

Parent staticMethod run 
Son staticMethod run 
Son method run

从结果可以看出:对于静态方法在子类中是不存在“重写”这一说的,就像前面我们提到的,用static关键字修饰的方法和变量都是属于类自己本身的,即使存在继承关系,子类并没有继承父类的static修饰的变量和方法,所以说即使子类和父类中都有同样的static方法和变量,他们是没有任何关系的,他们是相互独立的,他们是属于各自类本身的。因此也是不存在多态特性的。而对于普通方法的调用是存在“重写”而最终呈现出多态特性的。

同样的道理:对于static修饰的变量,当子类与父类中存在相同的static变量时,也是根据“静态引用”而不是根据“动态引用”来调用相应的变量的。

而在父类和子类中对于非static变量和方法,是根据“动态引用”来调用相应的变量和方法。

然而,接着会有这样的问题存在:java中 子类会不会继承父类的static变量和static方法

1)先说static方法:子类会不会继承父类的static方法呢??答案是:不会的,但是是可以访问的。

看如下的代码

public class Parent {
    public static void staticMethod(){ System.out.println("Parent staticMethod run"); } } public class Son extends Parent { //... }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

测试类

package com.wrh.teststaticmethod;

public class Test {

    public static void main(String[] args) { Parent child=new Son(); child.staticMethod();//输出:Parent staticMethod run Son s=new Son(); s.staticMethod();//输出:Parent staticMethod run } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

运行结果如下

Parent staticMethod run 
Parent staticMethod run

从上面的运行结果可以看出,static方法是可以被子类访问的。

2)接着来看父类的static修饰的变量,是否能够被子类继承呢?? 
答案:也是不可以的。但是也是可以被子类访问的。

小结

1)子类是不继承父类的static变量和方法的。因为这是属于类本身的。但是子类是可以访问的。 
2)子类和父类中同名的static变量和方法都是相互独立的,并不存在任何的重写的关系。

猜你喜欢

转载自blog.csdn.net/qiuzhongweiwei/article/details/80699374