java静态方法和静态属性到底能不能被继承?

java中的静态方法或是静态属性能不能被继承

先来做一个实验

//父类
class Father{

	public static String str = "Father类中的静态属性";
    public  String s = "Father中的非静态属性";
	public static  void fun(){
		System.out.println("Father类中的静态方法");
	}
	public void f(){
		System.out.println("Father中的非静态方法");
	}
}

class Child1 extends Father
{
	public static String str = "Child1改写Father中的静态属性";
	public String s = "Child1改写Father中的非静态属性";
	public static  void fun(){
		System.out.println("Child1改写Father中的静态方法");
	}
	public void f(){
		System.out.println("Child1改写Father中的非静态方法");
	}
}	
//完全继承,不修改
class Child2 extends Father
{
}

//定义测试类
public class TestExtends
{
	public static void main(String[] args){
   System.out.println("*****************Child2 ch1 = new Child2() 完全继承******************");
		//用子类实例化子类
   Child2 ch1 = new Child2();
   System.out.println(ch1.str);
   System.out.println(ch1.s);
   ch1.fun();
   ch1.f();

   System.out.println("*****************Father ch2 = new Child2() 完全继承 多态******************");

    //用父类引用指向子类对象
   Father ch2 = new Child2();
   System.out.println(ch2.str);
   System.out.println(ch2.s);
   ch2.fun();
   ch2.f();

	System.out.println("***************Child1 ch3 = new Child1()(Child1中修改了)********************");

   Child1 ch3 = new Child1();
   System.out.println(ch3.str);
   System.out.println(ch3.s);
   ch3.fun();
   ch3.f();

   System.out.println("*****************Father ch4 = new Child1()(Child1中修改了) 多态******************");

    //用父类引用指向子类对象
   Father ch4 = new Child1();
   System.out.println(ch4.str);
   System.out.println(ch4.s);
   ch4.fun();
   ch4.f();

	}
}


运行结果为:
在这里插入图片描述

结论:java中的静态属性和静态方法是可以被继承的,但是不能被子类重写

原因:

  • java中的静态方法、静态属性都属于静态绑定,父类中的静态属性和静态方法是可以继承到子类中的,但是不能被子类重写或者是覆盖。多态是动态绑定…只有动态绑定才会形成多态。静态属性和静态方法只是可以继承并不会表现出出多态性。
  • 静态的(即被static修饰的)在编译期就绑定了,而实例化的时候时候,父类引用指向子类对象是运行期才绑定

java不推荐用实例对象去调用静态方法、静态属性。所以个人认为纠结于静态方法能不能被重写意义并不大

猜你喜欢

转载自blog.csdn.net/qq_37823003/article/details/107655657