前往顾页
以后地位: 主页 > 收集编程 > Jsp实例教程 >

java中的static范例利用概述

时候:2011-03-22 11:21来源:知行网www.zhixing123.cn 编辑:麦田守望者

class Mountain{
static String name = "Himalaya";
static Mountain getMountain(){
System.out.println("Getting name");
return null;
}

public static void main(String[] args){
System.out.println(getMountain().name);
}
}

This program will run and print 'Getting Name' and 'Himalaya';

This question demonstrates that a null reference may be used to access a class (static) variable without causing an exception .
Note that, getMountain() is not a reference of a method. Note the method signature, it returns a reference to an object of class Mountain. So getMountain().name means we are accessing 'name' field of the object returned by the method. Now, as the field 'name' is static, the compiler notices this and figures out that it does not need an object of Mountain class to access 'name'. So even if the method returns null at run time, it doesn't matter because the compiler has already figured out the value of name.

顶一下
(0)
0%
踩一下
(0)
0%
------分开线----------------------------
标签(Tag):Java JAVA实例教程 java法度代码
------分开线----------------------------
颁发评论
请自发遵循互联网相关的政策法规,严禁公布色情、暴力、革命的谈吐。
评价:
神色:
考证码:点击我更换图片
猜你感兴趣