Previously, the polymorphism has always been very vague, today is free, I have a special test.
Bean classes to operate on
//Non-static variables class A{ int a = 1; } class B extends A{ int a = 3; int b = 2; } //Static variables class AA{ static int a = 1; } class BB extends AA{ static int a = 2; } class CC extends AA{ static int a = 3; } class M1{ static void show(){ System.out.println("M1.show()"); } } class M2 extends M1{ static void show(){ System.out.println("M2.show()"); } } public class Bean { }
***********************************************************************************************************************************************
Test class
import org.junit.Test; public class Test1 { //Non-static variables can be inherited (int a) @Test public void test1(){ A a = new A(); System.out.println(a.a);//1 B b = new B(); System.out.println(b.a);//1 System.out.println(b.b);//2 } //Non-static variables are determined at compile time and cannot be overridden. In fact, rewriting is about methods. @Test public void test2(){ B b = new B(); System.out.println(b.a);//3 System.out.println(b.b);//2 A ab = new B(); System.out.println(ab.a);//1 //b cannot be resolved or is not a field //System.out.println(ab.b);//1 } //Static variables can be inherited @Test public void test3(){ AA aa = new AA(); System.out.println(aa.a);//1 System.out.println(AA.a);//1 //Variables with the same name of different types are not declared in BB BB bb = new BB(); /*System.out.println(bb.a);//1 System.out.println(BB.a);//1 */ //If a non-static variable int a = 2 with the same name is declared to subclass BB; /*System.out.println(bb.a);//2 System.out.println(BB.a);//Compile and report errors */ //If a static variable statiint a = 2 with the same name is declared to subclass BB; System.out.println(bb.a);//2 System.out.println(BB.a);//2 } //Static variables cannot be overridden either @Test public void test4(){ AA ac = new CC(); //Variables with the same name of different types are not declared in CC //System.out.println(ac.a);//1 //If a non-static variable int a = 2 with the same name is declared to subclass CC; System.out.println(ac.a);//1 //If a static variable statiint a = 2 with the same name is declared to subclass BB; System.out.println(ac.a);//1 } //Static methods can be inherited @Test public void test5(){ M2 m2 = new M2(); m2.show();//M1.show() M2.show();//M1.show() } //Static methods cannot be overridden @Test public void test6(){ M1.show();//M1.show() M2.show();//M2.show() //If a static void show() method with the same name and parameter is declared in subclass M2, then the static method of the parent class is hidden. M2 m2 = new M2(); m2.show();//M2.show() //Upward transition (polymorphism) parent static methods are not rewritten M1 m12 = new M2(); m12.show();//M1.show(), indicating that the parent static method was not overridden } }