A very important concept for Java is polymorphism, but many of the pits inside the polymorphic are easily overlooked, and here I summarize the pits I have encountered.
1, for the domain and static methods, there is no polymorphism. The demo is as follows:
PackageCom.zh.model; Public classTest2 { Public intindex = 0; Public intGetIndex () {returnindex; } Public Static voidMain (string[] args) {Test2 test2=NewChild (); System.out.println ("test2.index=" +test2.index+ "test2.getindex () =" +Test2.getindex ()); Child Child=NewChild (); System.out.println ("child.index=" +child.index+ "child.getindex () =" +Child.getindex ()); }}classChildextendstest2{ Public intindex = 1; Public intGetIndex () {returnindex; } Public intGetsuperindex () {return Super. Index; }}
The output is:
2. When there is no default constructor for the parent class, when there is a constructor with parameters, the child class must explicitly write a statement called the parent class constructor super (...). )
, you will get an error if you do not use the Super keyword explicitly.
3. the polymorphic load order when referencing objects of the parent class type to the object of the subclass: that is, the parent parent = new Children () is executed in the main ' method;
Load the static initialization of the base class----The subclass static initialization of the basic class----。。。。 -----The static initialization of the class-----all the basic types in the object are initialized to the default values, the reference type is set to NULL-----Call the parent class constructor----call the subclass Builder
Class Parent {
public static int parent = 1;
static {
SYSTEM.OUT.PRINTLN (parent);
}
Public Parent () {
System.out.println ("Parent");
}
public static void Main (string[] args) {
Parent AAA = new Children ();
}
}
Class Children extends parent{
public static int children = 2;
static {
System.out.println (children);
}
Public children () {
System.out.println ("Children");
}
}
Output:
Understanding of Java Polymorphism