java中使用static要注意什么
作者:归人云淡风轻
时间:2023-05-02
浏览:2
1、使用static方法的时候,只能访问static声明的属性和方法,而非static声明的属性和方法是不能访问的。packagecom.jk.ref;classPeople{Stringname;privatestaticStringcountry="中国";publicPeople(Stringname){this.name=name;}publicvoidtell(){System.out.println("name:"+name+""+"country:"+country);}/***@retur
本文目录
1、使用static方法的时候,只能访问static声明的属性和方法,而非static声明的属性和方法是不能访问的。
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、父类引用只能调父类和子类重写方法,父子同名方法不会覆盖而是遮蔽。
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”);
}
}
作者最新文章
AO3中文界面设置指南与核心功能使用教程
2026-10-14 23:28
解决win10运行3DMAX自动重启的方法
2026-10-13 17:08
哔哩哔哩投稿封面上传失败怎么解决
2026-10-13 15:55
漫蛙漫画官网免费漫画入口
2026-10-13 13:19
漫蛙漫画app免费下载安装最新版
2026-10-13 13:18
上一篇:
Java设计模式之抽象工厂模式怎么实现
下一篇:
Python 获取线程返回值的三种方式
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































