2016年1月19日 static声明属…


class Person11{
private String name;
private int age;
static String city="A城";//这里运用static关键字之后,改为了公共.
public Person11(String name,int age){
this.name=name;
this.age=age;
}
public String getInfo(){
return "姓名:"+this.name+"年龄:"+this.age+"城市:"+this.city;
}
}
public class StaticDemo02 {
public static void main(String args[]){
Person11 per1=new Person11("张三",30);
Person11 per2=new Person11("李四",31);
Person11 per3=new Person11("王武",32);
System.out.println("信息修改之前");
System.out.println(per1.getInfo());
System.out.println(per2.getInfo());
System.out.println(per3.getInfo());
System.out.println("信息修改之后");
Person11.city="B城";//注意,此处应有类直接更改。
System.out.println(per1.getInfo());
System.out.println(per2.getInfo());
System.out.println(per3.getInfo());
}
}
运行结果:
信息修改之前
姓名:张三年龄:30城市:A城
姓名:李四年龄:31城市:A城
姓名:王武年龄:32城市:A城
信息修改之后
姓名:张三年龄:30城市:B城
姓名:李四年龄:31城市:B城
姓名:王武年龄:32城市:B城

以上是static声明属性的用法。
static还可以定义方法,上面的代码虽然实现了更改,但是在外部直接修改内部的属性,这样会不安全
所以,应该将city设为private 这样外部不能直接更改,下面的代码通过增加静态的方法,来修改
city从而实现。

class Person12{
private String name;
private int age;
private static String city="A城";//封装
public static void setCity(String c){//静态方法
city=c;
}
public Person12(String name,int age){
this.name=name;
this.age=age;
}
public String getInfo(){
return "姓名:"+this.name+"年龄:"+this.age+"城市:"+this.city;
}
}
public class StaticDemo03 {
public static void main(String args[]){
Person12 per1=new Person12("张三",30);
Person12 per2=new Person12("李四",31);
Person12 per3=new Person12("王武",32);
System.out.println("信息修改之前");
System.out.println(per1.getInfo());
System.out.println(per2.getInfo());
System.out.println(per3.getInfo());
System.out.println("信息修改之后");
//Person12.city="B城";封装后外部将无法直接个更改
Person12.setCity("B城");//调用方法来修改内容
System.out.println(per1.getInfo());
System.out.println(per2.getInfo());
System.out.println(per3.getInfo());
}
}
注意①:static只能调用静态属性,不能调用非静态方法,而非静态方法可以调用静态属性和方法。
如果需要在静态主方法中调用非静态方法,可以写以下代码。
public class StaticDemo05 {
public static void main(String args[]){
new StaticDemo05().fun();
}
public void fun(){
System.out.println("hello world!");
}
}


对象数组的学习
class Person14{
private String name;
private int age;
public Person14(String name,int age){
this.name=name;
this.age=age;
}
public String getInfo(){
return "姓名:"+this.name+",年龄"+this.age;
}
}
public class ObjectDemo01 {
public static void main(String args[]){
Person14 p[]=new Person14[3];
for(int x=0;x
System.out.print(p[x]+"、");
}
    System.out.println();
p[0]=new Person14("张三",30);
p[1]=new Person14("李四",31);
p[2]=new Person14("王武",32);
for(int x=0;x
System.out.println(p[x].getInfo());
}
}
}

构造方法私有化
class Single{
private static Single instance=new Single();
private Single(){//构造方法私有化
}
public static Single getInstance(){
return instance;
}
public void print(){
System.out.println("hello world!");
}
}
public class SingleDemo01 {
public static void main(String args[]){
Single s=null;//声明对象
s=Single.getInstance();//实例化对象
s.print();
}
}

你可能感兴趣的:(2016年1月19日 static声明属…)