Java:如何在类中包含全局值?

hhh*_*hhh -7 java global-variables

我想要更少的方法.我想要一个通用的全局TestClass,我可以从中使用它在类中的任何值.

import java.util.*;
import java.io.*;

public class TestClass {
        TestClass(String hello){
                String hallo = hello;
                String halloSecond = "Saluto!";
        }
        public static void main(String[] args) {
                TestClass test = new TestClass("Tjena!");
                System.out.println("I want "Tjena!": " + test.hallo);
                TestClass testSecond = new TestClass("1");
                System.out.println("I want Saluto!:" + test.halloSecond);
                System.out.println("I want Saluto!:" + testSecond.halloSecond);

                // How can I get glob.vars like the "Saluto!"?
        }
}
Run Code Online (Sandbox Code Playgroud)

[澄清需要]我无法理解GLOB.VARS的不使用.请参阅下面的代码,在没有实例的情况下无法访问GLOB.VARS,因此出现错误.如果我保证没有恶意代码可以创建实例,使用GLOB.vars有什么问题吗?

$ javac TestClass.java 
TestClass.java:19: non-static variable hallo cannot be referenced from a static context
  System.out.println("It did not get to the GLOB.VAR: " + hallo);
                                             ^
1 error
$ cat TestClass.java 
import java.util.*;
import java.io.*;

public class TestClass {
        public String hallo;
        public String halloSecond;

        TestClass(String hello){
                hallo = hello;
                halloSecond = "Saluto!";
        }
        public static void main(String[] args) {
                TestClass test = new TestClass("Tjena!");
      System.out.println("It did not get to the GLOB.VAR" + hallo);
        }
}
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 9

我想要更少的方法.

你不应该.方法不应按计数或大小来衡量.如果他们有单独的责任,他们应该存在.

我想要一个通用的全局TestClass,我可以从中使用它在类中的任何值.

这没有多大意义.我想你需要实例变量

 private String hello;
 private String helloSecond;

 TestClass(String hello){
        hallo = hello;
        halloSecond = "Saluto!";
 }

 public String getHello() { return hello; }
 public String getHelloSecond() { return helloSecond; }
Run Code Online (Sandbox Code Playgroud)

如何在一个类中拥有全局值?

全局变量可以通过定义它们来实现static:

public static String var;
Run Code Online (Sandbox Code Playgroud)

但使用这些是一种非常糟糕的做法.你不能使用它们.


Mic*_*rdt 5

全局变量通常被认为是一个非常糟糕的想法.是的,设计类可能很困难,因此每个类都包含完成其工作所需的所有(或大多数)变量.但是处理基于全局变量的代码要困难得多(主要是因为很难预测代码的一部分对其余部分的影响会有什么影响).