In terms of the use of keywords, we already know something about the static method. In order to prevent unnecessary errors when using it, everyone must understand its scope of use. This article divides the points to note when using static into two aspects, one is the scope of access, and the other is the note about method invocation. Let’s take a look at the complete points to note when using static.
1. When using static methods, you can only access statically declared properties and methods, but non-statically declared properties and methods cannot be accessed.
package com.jk.ref; class People{ String name; private static String country="China"; public People(String name){ this.name=name; } public void tell(){ System.out.println("name:"+name+" "+"country:"+country); } /** * @return the country */ public static String getCountry() { return country; } /** * @param country the country to set */ public static void setCountry(String country) { People.country = country; } } public class StaticDemo01 { public static void main(String[] args) { // TODO Auto-generated method stub People.setCountry("shanghai"); People ps1=new People("zhangsan"); //People.country="Shanghai"; ps1.tell(); People ps2=new People("lisi"); // ps2.country="Shanghai"; ps2.tell(); People ps3=new People("wangwu"); // ps3.country="Shanghai"; ps3.tell(); } }
2. The parent class reference can only adjust the overridden methods of the parent class and the child class. Methods with the same name of the parent and child will not be overwritten but obscured.
public class TestMain { public static void main(String[] args) { Super sup = new Sub(); //Encapsulation (upward shaping) sup.m1(); //The parent class reference cannot adjust the unoverridden method of the subclass, and outputs mi in Super sup.m2();//Call the subclass method m2, inherit and build the parent class method first, overwrite (rewrite) the method with the same method name, and output m2 in Sub Sub sub = (Sub)sup; //Unboxing (shape downward) sub.m1(); //Call the subclass static method m1, first build the parent class method, the method name is the same, the method name is the same masking method, output m2 in Sub sub.m2();//Call the subclass method m2, inherit and build the parent class method first, overwrite (rewrite) the method with the same method name, and output m2 in Sub } } class Super{ //Parent class public static void m1() { //Parent class static method System.out.println(“m1 in Super”); } public void m2() { //Parent class method System.out.println(“m2 in Super”); } } class Sub extends Super{ //Subclass public static void m1() { //Subclass static method System.out.println(“m1 in Sub”); } public void m2() { //Subclass method System.out.println(“m2 in Sub”); } }
The above are the points to note when using static in Java. During specific operations, be sure not to ignore these two usage items. This is also a common error point that novices often encounter when practicing.