java中使用static要注意什么

这篇文章主要介绍“java中使用static要注意什么”,在日常操作中,相信很多人在java中使用static要注意什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”java中使用static要注意什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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

到此,关于“java中使用static要注意什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注蜗牛博客网站,小编会继续努力为大家带来更多实用的文章!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接