首页 > 代码库 > Java Static关键字之小程序
Java Static关键字之小程序
对于学习static我们先来看两个例子:
1 public class Cat { 2 private static int sid = 0; 3 private String name; 4 int id; 5 Cat(String name) { 6 this.name = name; 7 id = sid++; 8 } 9 public void info(){ 10 System.out.println 11 ("My name is "+name+" No."+id); 12 } 13 public static void main(String arg[]){ 14 15 Cat.sid = 100; 16 Cat mimi = new Cat("mimi");17 Cat pipi = new Cat("pipi"); 18 mimi.info(); 19 pipi.info(); 20 } 21 }
运行结果为: My name is mimi No.100 My name is pipi No.101
1 public class Cat { 2 private int sid = 0; 3 private String name; 4 int id; 5 Cat(String name) { 6 this.name = name; 7 id = sid++; 8 } 9 public void info(){ 10 System.out.println 11 ("My name is "+name+" No."+id); 12 } 13 public static void main(String arg[]){ 14 15 // Cat.sid = 100; 16 Cat mimi = new Cat("mimi"); 17 Cat pipi = new Cat("pipi"); 18 mimi.info(); 19 pipi.info(); 20 } 21 }
运行结果为: My name is mimi No.0 My name is pipi No.0
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。