java中使用static要注意什么
作者:归人云淡风轻
时间:2023-04-28
来源:互联网
浏览:0
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”);
}
}
作者最新文章
荣耀MagicOS 11发布计划与Agent Harness架构解析
2026-09-08 19:23
AI重构企业业务架构:超聚变“智企”范式核心解析
2026-09-08 18:39
PDF合并工具怎么选?在线合并5步实操指南
2026-09-04 17:05
PDF图片压缩工具推荐与批量处理实操指南
2026-09-03 12:14
照片如何转成PDF格式?三种图片转PDF操作方法
2026-09-03 11:04
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















