我被问到这个问题,为什么我不能将所有方法声明为静态?你能在这里给我一个解释吗?谢谢。
我相信当您将方法设为静态时,它不能访问非静态成员?
你可以。没有理由从这样的类中实例化对象。任何状态在 JVM 中都是全局的。
您的提问者可能将“不能”与“不应该”混淆了。
静态方法不能访问实例变量。:)
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
}
}
您可以将所有方法声明为,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
}
将所有方法设为静态是实用程序类中的好习惯。
你可以。但结果将是一个使用现有类的结构化程序(想想 C、Pascal),而不是真正的 OOP。面向对象是 Java 编程的惯用方法,因此请尽量减少代码中的静态关键字数量。
没有这样的克制。您可以将类中的所有方法设为静态。在 C# 中,您甚至可以将类本身定义为静态(要求其中的所有方法都是静态的)。
这更多的是您想通过该课程实现什么的问题。
您可以将所有方法定义为静态的。这取决于你是否应该或不应该的上下文。最好的选择是制作静态库方法。例如,下面是我创建的 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^^^^^^^");
}
}
您可以将所有内容声明为静态。但是什么样的正常比例对象模型需要所有方法都是静态的,这是一个大问题
是的,你可以取决于你的需要。但是请记住“this”关键字在这种情况下将不起作用,您无法访问公共成员!