1. When using the static method, 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="中国"; 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="上海"; ps1.tell(); People ps2=new People("lisi"); // ps2.country="上海"; ps2.tell(); People ps3=new People("wangwu"); // ps3.country="上海"; 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(); //封装(向上造型) sup.m1(); //父类引用无法调子类未重写方法,输出mi in Super sup.m2();//调用子类方法m2,继承先构建父类方法,方法名相同覆盖(重写)方法,输出m2 in Sub Sub sub = (Sub)sup; //拆箱(向下造型) sub.m1(); //调用子类静态方法m1,先构建父类方法,方法名相同方法名相同遮蔽方法,输出m2 in Sub sub.m2();//调用子类方法m2,继承先构建父类方法,方法名相同覆盖(重写)方法,输出m2 in Sub } } class Super{ //父类 public static void m1() { //父类静态方法 System.out.println(“m1 in Super”); } public void m2() { //父类方法 System.out.println(“m2 in Super”); } } class Sub extends Super{ //子类 public static void m1() { //子类静态方法 System.out.println(“m1 in Sub”); } public void m2() { //子类方法 System.out.println(“m2 in Sub”); } }
The above is the detailed content of What should you pay attention to when using static in java?. For more information, please follow other related articles on the PHP Chinese website!