实例方法和类方法
Date4_ex.java *
Date4_ex.java 2012-7-229:35
1publicclassDate4
2{
3 privateintyear,month,day; //实例变量,私有
4 staticintcount=0; //类变量
5 publicDate4(int y,int m,int d)
6 {
7 year=y;
8 month=((m>=1)&(m<=12))?m:1;
9 day=((d>=1)&(d<=31))?d:1;
10 count++;
11 }
12 publicstaticvoidprint_count() //类方法,只能访问类变量
13 {
14 System.out.println("count="+count+" ");
15 }
16 publicvoidprint() //实例方法,可以访问类变量和实例变量
17 {
18 print_count(); //调用类方法;
19 System.out.println("dateis"+year+"-"+month+"-"+day);
20 }
21 publicvoidfinalize() //折构方法
22 {
23 count--;
24 System.out.println("count="+count+" ");
25 }
26}
27
28classDate4_ex
29{
30 publicstaticvoidmain(Stringargs[])
31 {
32 Date4a=newDate4(2012,7,21);
33 System.out.println("----------a.print_count();---------");
34 a.print_count();
35 System.out.println("----------a.print();---------------");
36 a.print();
37 Date4b=newDate4(2012,12,30);
38 System.out.println("----------b.print();---------------");
39 b.print();
40 System.out.println("----------a.finalize();------------");
41 a.finalize();
42 System.out.println("----------b.print_count();---------");
43 Date4.print_count();
44 }
45}
46
输出结果:
E:\src\chapter3>java Date4_ex
----------a.print_count();---------
count=1
----------a.print();---------------
count=1
date is 2012-7-21
----------b.print();---------------
count=2
date is 2012-12-30
----------a.finalize();------------
count=1
----------b.print_count();---------
count=1
<![if !vml]><![endif]>页1共1