Topic: 怎样引用public的非静态变量?

  Print this page

1.怎样引用public的非静态变量? Copy to clipboard
Posted by: ggloverv
Posted on: 2008-10-26 21:03

public class Shit {
  public int i=2;
  public static int j=3;
  public static void main(String[] args) {
    System.out.println(i);//有错
    System.out.println(j);
  }

}


怎样才能输出那个i呢?

2.Re:怎样引用public的非静态变量? [Re: ggloverv] Copy to clipboard
Posted by: ice0819
Posted on: 2008-10-27 17:23

Shit shit=new Shit();
System.out.println(shit.i);

3.Re:怎样引用public的非静态变量? [Re: ggloverv] Copy to clipboard
Posted by: winoo7
Posted on: 2008-10-28 08:43

Shit s = new Shit();
System.out.println(s.i);

4.Re:怎样引用public的非静态变量? [Re: ggloverv] Copy to clipboard
Posted by: gbluo
Posted on: 2008-10-28 09:23

还有别的方法吗?

5.Re:怎样引用public的非静态变量? [Re: gbluo] Copy to clipboard
Posted by: JiafanZhou
Posted on: 2008-11-11 22:17

gbluo wrote:
还有别的方法吗?

No! It is the only mean to get access to the non-static member field. The reason for this is that non static member fields or methods are bounded to a specific instance of the object. Thus it will be forced to be manipulated by the instance reference.

Another thing worth to be mentioned is that it is *not* recommended to declare public to member fields. It would be preferred to declare public get/set methods, in conformance with the JavaBean standard. And it is subject to one of the most important OO rule: Encapsulation.

By the way, why do you declare your class name as "SHXT"? It is a forbidden keyword in the Java World.... Smile

Regards,
Jiafan


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923