为什么其他方法可以是“静态的"?但是构造函数不能? [英] Why can other methods be "static" but a constructor cannot?

查看:31
本文介绍了为什么其他方法可以是“静态的"?但是构造函数不能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么 main 方法必须是静态的.我了解静态变量,但静态方法对我来说很难掌握.是否存在静态方法,以便可以在两个不同的类中创建两个同名的方法,并且不会相互冲突?

I do not understand why the main method has to be static. I understand static variables but static methods are difficult for me to grasp. Do static method exists so that one can create two methods with the same name in two different classes that won't clash with each other?

另外,我不明白为什么我不能创建静态构造函数.

Also, I don't understand why I can't create a static constructor.

谁能帮忙解释一下这个概念?

Could anyone help explain this concept?

推荐答案

Java 有 [静态构造函数] 静态初始化块,可以看作是一个静态构造函数":

Java has [static constructors] static initialization blocks which can be viewed as a "static constructor":

class Foo {
  static String Bar;
  static {
     // "static constructor"
     Bar = "Hello world!";
  }
}

无论如何,主类中唯一必须是静态的方法是main方法.这是因为它被调用而没有首先创建主类"的实例.一种常用的技术,也是我更喜欢的一种,是快速摆脱静态上下文:

In any case, the only method in the main class which must be static is the main method. This is because it is invoked without first creating an instance of the "main class". A common technique, and the one I prefer, is to quickly get out of static context:

class Main {
   int argCount;

   // constructor
   public Main (String[] args) {
     // and back to boring ol' non-static Java
     argCount = args.length;       
   }

   void runIt () {
      System.out.println("arg count: " + argCount);
   }

   // must be static -- no Main instance created yet
   public static void main (String[] args) {
      Main me = new Main(args);
      me.runIt();
   }
}

此外,静态与名称冲突"无关.静态方法(或变量)只是一种与类型的特定实例相关联的方法(或变量).我建议通读 Classes and Objects Java Tutorial了解实例和类变量.

Also, static has nothing to do with "name clashes". A static method (or variable) is simply a method (or variable) that is not associated with a specific instance of a type. I would recommend reading through the Classes and Objects Java Tutorial and the section Understanding Instance and Class Variables.

快乐编码.

这篇关于为什么其他方法可以是“静态的"?但是构造函数不能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆