4

我被问到这个问题,为什么我不能将所有方法声明为静态?你能在这里给我一个解释吗?谢谢。

我相信当您将方法设为静态时,它不能访问非静态成员?

4

9 回答 9

5

你可以。没有理由从这样的类中实例化对象。任何状态在 JVM 中都是全局的。

您的提问者可能将“不能”与“不应该”混淆了。

于 2012-07-19T07:31:52.020 回答
4

静态方法不能访问实例变量。:)

public class MyStaticExample{
  private String instanceVariable = "Hello";
  private static String STATIC_VARIABLE = "Hello too";

  public static void staticMethod(){
    System.out.println(this.instanceVariable); // this will result in a compilation error.
    System.out.println(STATIC_VARIABLE); // this is ok
  }

  public void instanceMethod(){
    System.out.println(this.instanceVariable); // this is ok
    System.out.println(STATIC_VARIABLE); // this is ok
  }
}
于 2012-07-19T07:31:42.883 回答
2

可以将所有方法声明为,static但随后您的方法将变为类级别。假设您创建了 10 个具有不同状态的对象,其中状态由properties. 那么在这种情况下,您将无法state使用static方法获取对象。

Object obj;
public static Object getState(){

    return obj; // compile time error Cannot make a static reference to the non-static field 
}

将所有方法设为静态是实用程序类中的好习惯。

于 2012-07-19T07:34:53.993 回答
2

你可以。但结果将是一个使用现有类的结构化程序(想想 C、Pascal),而不是真正的 OOP。面向对象是 Java 编程的惯用方法,因此请尽量减少代码中的静态关键字数量。

于 2012-07-19T07:35:39.727 回答
2

我将从课程:面向对象编程概念开始,然后从 JDK 中选择几乎所有类。一个简单的开始是Boolean,它需要两个实例,一个用于 TRUE,一个用于 FALSE,无法使用静态方法实现。

于 2012-07-19T07:42:55.773 回答
1

没有这样的克制。您可以将类中的所有方法设为静态。在 C# 中,您甚至可以将类本身定义为静态(要求其中的所有方法都是静态的)。

这更多的是您想通过该课程实现什么的问题。

于 2012-07-19T07:36:25.163 回答
1

您可以将所有方法定义为静态的。这取决于你是否应该或不应该的上下文。最好的选择是制作静态库方法。例如,下面是我创建的 TestHelper 实用程序类 -

public class TestHelper {
    /**
     * Method echo.
     * 
     * @param heading
     *            String
     */
    public static void echo(String heading) {
        System.out.println("+++++++++++++++++++++++++");
        System.out.println("++++++ " + heading + " ++++++");
    }

    public static void end() {
        System.out.println("=========================");
    }

    public static void mark() {
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
    }

    /**
     * Method spot.
     * 
     * @param string
     *            String
     */
    public static void spot(Object string) {
        System.out.println("*****_______" + string + "_______******");
    }

    /**
     * This is a stub method
     */
    public static void stub() {

    }

    public static void error(String string) {
        System.out.println("^^^^^^^^^^^Error Begining^^^^^^^^^^^^^^");
        System.out.println(string);
        System.out.println("^^^^^^^^^^^Error End^^^^^^^");
    }
}
于 2012-07-19T07:41:00.900 回答
0

您可以将所有内容声明为静态。但是什么样的正常比例对象模型需要所有方法都是静态的,这是一个大问题

于 2012-07-19T07:34:59.770 回答
0

是的,你可以取决于你的需要。但是请记住“this”关键字在这种情况下将不起作用,您无法访问公共成员!

于 2012-07-19T07:38:09.463 回答