Home> Java> javaTutorial> body text

What should you pay attention to when using static in java?

PHPz
Release: 2023-04-18 14:43:03
forward
726 people have browsed it

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(); } }
Copy after login

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”); } }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!