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

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

问题描述

我不明白为什么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有 [static constructors] 静态初始化块,可以看作是一个静态构造函数:

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();
   }
}

此外,static与名称冲突无关。静态方法(或变量)仅仅是与类型的特定实例相关联的方法(或变量)。我建议您阅读类和对象Java教程,以及了解实例和类变量部分。

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天全站免登陆