作者webberhan (c'est la vie)
看板java
标题Re: [问题] JAVA如何设定全域变数
时间Mon Oct 16 14:43:11 2006
假设需求是让两个类别的实体能一起使用同一个变数
由於基本型别无法做到call by reference, 所以使用wrapper
个人觉得在非多执行绪的情况下
实在能不用static变数就不要用
在main function中定义一个变数其实就够用了, 不是吗?
我觉得比较安全的做法如下
public class Class1 {
public Class1(MyInt integer) {
this.integer = integer;
this.integer.setInteger(100);
}
private final MyInt integer;
public static void main(String[] args) {
final MyInt integer = new MyInt(0);
Class1 c1 = new Class1(integer);
Class2 c2 = new Class2(integer);
}
}
class Class2 {
public Class2(MyInt integer) {
this.integer = integer;
this.integer.setInteger(200);
}
private final MyInt integer;
}
class MyInt {
public MyInt(int integer) {
this.integer = integer;
}
private int integer;
public int getInteger() {
return integer;
}
public void setInteger(int integer) {
this.integer = integer;
}
}
※ 引述《[email protected] (暑假作业真多..泣)》之铭言:
: 全域变数应该第一个想到的是static吧,
: class B {
: static int i=0;
: }
: public class A{
: public static void main(String[] args){
: B.i = +2;
: System.out.println(B.i);
: }
: }
: 这样是不是也可行呢,而且static variable是放在记忆体中Global的区块喔
: ※ 引述《[email protected] (foolish)》之铭言:
: > 目标虽然达成了。但这实在是一个bad style
--
And I don't think that I'll see her again,
But we shared a moment that will last till the end.
You're beautiful. You're beautiful.
You're beautiful, it's true.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.130.197.139
※ 编辑: webberhan 来自: 220.130.197.139 (10/16 14:46)
※ 编辑: webberhan 来自: 220.130.197.139 (10/16 14:51)