使用static声明方法

来源:互联网 发布:windows中的文件属性 编辑:程序博客网 时间:2024/05/29 13:56
package lkp;class Person{private String name;private int age;static String country = "A city"; // 使用static定义城市属性public static void setCountry(String c){//定义static方法country  = c;//修改static属性}public Person(String name,int age){   //通过构造为属性赋值this.name = name;this.age = age;}public void info(){System.out.println("姓名: " + this.name + " 年龄: "  + this.age + " 城市: " + country);}public static String getCountry(){//取得static属性return country;} }public class Test{public static void main(String args[]){Person per1 = new Person("张三",20);Person per2 = new Person("李四",21);Person per3 = new Person("王五",23);System.out.println("--------- 修改前-----------");per1.info();per2.info();per3.info();System.out.println("--------- 修改后-----------");Person.setCountry("B city");  //使用类名称修改static属性的内容per1.info();per2.info();per3.info();}}        /*    非static声明的方法可以去调用static声明的属性或方法,    但是static声明的方法是不能调用非static类型声明的属性或方法    */

0 0
原创粉丝点击