This article uses examples to illustrate the differences between static and non-static methods in Java. At the end of the article, I will give a detailed explanation.
First, we provide two classes. The base class is parent and the derived class is child. In parent, we provide two methods: static method staticmethod () and non-static method nonstaticmethod (). We cover two methods in the Child class.
Class Parent
{
Public void nonstaticmethod ()
{
System. Out. println ("Parent's non-static method is called ");
}
Public static void staticmethod ()
{
System. Out. println ("Parent's static method is called ");
}
}
Class Child extends parent
{
Public void nonstaticmethod ()
{
System. Out. println ("Child's non-static method is called ");
}
Public static void staticmethod ()
{
System. Out. println ("Child's static method is called ");
}
}
In the test class, we use parent p1 = new parent (), parent P2 = new child (), and child C = new child () to get three instances, and respectively call static and non-static methods. Let's look at the running results of the program.
Public class test
{
Public static void main (string ARGs [])
{
Parent p1 = new parent ();
Parent P2 = new child ();
Child C = new child ();
System. Out. Print ("parent. Static:"); parent. staticmethod ();
System. Out. Print ("p1.static:"); p1.staticmethod ();
System. Out. Print ("p2.static:"); p2.staticmethod ();
System. Out. Print ("p1.nonstatic:"); p1.nonstaticmethod ();
System. Out. Print ("p2.nonstatic:"); p2.nonstaticmethod ();
System. Out. Print ("child. Static:"); Child. staticmethod ();
System. Out. Print ("C. Static:"); C. staticmethod ();
System. Out. Print ("C. nonstatic:"); C. nonstaticmethod ();
}
}
The program runs as follows:
Parent. Static: parent's static method is called
P1.static: parent's static method is called
P2.static: parent's static method is called
P1.nonstatic: parent's non-static method is called
P2.nonstatic: Child's non-static method is called
Child. Static: Child's static method is called
C. Static: Child's static method is called
C. nonstatic: Child's non-static method is called
It is worth noting that P2 is actually a reference of the Child type. However, when calling a static method, it executes the static method of the parent class instead of the static method of the child, when calling the non-static method of P2, the child non-static method is executed. Why? The reason is that the static method matches the static method with the reference type of the class during compilation, rather than matching the class reference at runtime. Therefore, we conclude that the static method created in the subclass does not overwrite the static method with the same name in the parent class.
Reference: http://www.knowsky.com/363078.html