每天学点Java知识 ------> static关键字定义方法
上一篇 /
下一篇 2014-07-18 09:20:18
/ 个人分类:Java学习
例:使用static定义方法
class Person{
private String name;
private int age;
private static String country = "北京";
public Person(String name, int age){
this.name = name;
this.age = age;
}
public static String getCountry() {
return country;
}
public static void setCountry(String country) {
test.country = country;
}
public String getInfo(){
return "姓名:" +this.name + ",年龄:" + this.age + ",城市: " + this.country;
}
}
public class TestDemo{
public static void main(String args[]){
Person.setCountry("南京");
System.out.println(Person.getCountry());
Person per1 = new Person("张三",20);
System.out.println(per1.getInfo());
}
}
程序运行结果:
南京
姓名:张三,年龄20,城市:南京
本程序在Person类定义country属性时使用了static关键字定义,并且将属性封装,而且在外部操作country属性时就使用了static
定义的两个方法完成,同时可以清楚发现,static方法也可以通过类名称调用,并且在没有实例化对象时依然可以使用
收藏
举报
TAG: