2012年5月31日 星期四

Java Basic(47)-Static(2)


public class tuna {
private String first;
private String last;
private static int members = 0;
public tuna(String fn,String ln){
first = fn;
last = ln;
members++;
System.out.printf("Construtor for %s %s,members in the club: %d\n",first,last,members);
}
public String getFirst(){
return first;
}
public String getLast(){
return last;
}
public static int getMembers(){
return members;
}
}


class apples{
public static void main(String[] args){
tuna member1 = new tuna("Megan","Fox");
tuna member2 = new tuna("Natalie","Portman");
tuna member3 = new tuna("Taylor","Swift");
System.out.println(tuna.getMembers());
}
}

因為靜態方法是共享所有的對象

這是運行時的結果:
Construtor for Megan Fox,members in the club: 1
Construtor for Natalie Portman,members in the club: 2
Construtor for Taylor Swift,members in the club: 3

沒有留言:

張貼留言