java中的关键字static(静态变量)和final定义常量

 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值