上官瑞杰
勤能补拙是良训
 1 package point;
 2 
 3 class Point {
 4     
 5     int x = 0;
 6     int y = 0;
 7     static int z = 100; // 定义静态变量z,类变量
 8     static final double PI = 3.1415926;// final定义常量,它的值在运行时不能被改变
 9 
10     Point(int a, int b) {
11         //PI=3.1415926;
12         /*
13          * 当使用静态常量的时候,不能在构造函数中初始化, 因为静态时,常量已经变成类的常量了
14          */
15         x = a;
16         y = b;
17     }
18 
19     Point() {
20         this(1, 1); // 必须作为构造函数的第一条语句
21     }
22 
23     static void output() {
24         System.out.println("hello,output() called");
25         // System.out.println(x);//此时尚未给x,y分配内存空间,
26         /*
27          * Point2.java:16: non-static variable x cannot be referenced from a
28          * static context System.out.println(x); ^ 1 error
29          */
30         System.out.println(z);
31     }
32 
33     
34     @SuppressWarnings("static-access")
35     public static void main(String[] args) {
36         
37         Point.output();
38         /*
39          * 当声明output为静态方法(static)时,直接使用类名Point, 来调用output()方法,
40          * 因为这样一个静态方法只属于类本身, 而不属于某个对象,把这种方法称为类方法 而对于非静态方法,称之为实例方法,即对象的方法
41          */
42         Point pt2 = new Point();
43         pt2.output();
44         // 当然也可以使用类的实例,即对象pt2,使用pt2来调用静态方法
45         Point pt3 = new Point();
46         Point pt4 = new Point();
47         pt3.z = 5;
48         System.out.println(pt3.z);// 显示的是5,因为z是静态变量,类的变量
49         pt4.z = 1000;
50         System.out.println(pt3.z);// 显示的是1000,因为z是静态变量,类的变量
51         System.out.println(pt4.z);// 48句赋予了z新的值
52 
53     }
54 }
作者:Leo Chin
出处:http://www.cnblogs.com/hnrainll/
posted on 2014-08-06 20:06  上官瑞杰  阅读(514)  评论(0编辑  收藏  举报