为什么其他方法可以是“静态”的?但构造函数不能?

发布于 2024-12-09 18:56:34 字数 145 浏览 0 评论 0原文

我不明白为什么 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

染柒℉ 2024-12-16 18:56:34

Java 有 [静态构造函数] 静态初始化块 可以被视为“静态构造函数”:

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

在任何情况下,主类中唯一必须是静态的方法是 main 方法。这是因为它的调用没有首先创建“主类”的实例。一种常见的技术,也是我更喜欢的技术,是快速摆脱静态上下文:

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

此外,静态与“名称冲突”无关。静态方法(或变量)只是一个与特定类型实例关联的方法(或变量)。我建议阅读 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!";
  }
}

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

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.

Happy coding.

美人迟暮 2024-12-16 18:56:34

我正在分享“为什么 java 构造函数不是静态的”的原因之一。

简单地说,“java构造函数总是非静态的”,因为

构造函数的目的只是初始化/构造对象,并使继承成为可能。为此,我们需要使用两个有用的 java 关键字(兼非静态变量),例如 this 和 super。
我们将使用“this”来初始化该对象。
我们/Java将使用super(当然是super())来调用超类构造函数,以便首先创建超级对象(或对象类),然后创建子对象(因此继承)
如果构造函数是静态的,那么我们不能在构造函数中使用这两个关键字(非静态变量)(正如我们所知,非静态的东西不能从静态上下文中引用)

所以java构造函数不应该是静态的。

I am sharing one of the reason "why not a java constructor be static".

Simply to say, "A java constructor is always non static" because,

The purpose of the constructor is only to initialize/construct the object, and to make inheritance possible. To do these we need to use the two useful java keywords (cum non-static variables) such as this and super.
We will use 'this' to initialize the object.
We/Java will use super(ofcourse super()) to invoke super class constructor so that super object(or Object class) created first then the child object(hence the inheritance)
If the constructor is static then we cant use that two keywords(non-static variables) inside the constructor(As we know non-static stuff cant be referenced from static context)

So java constructors should not static.

心清如水 2024-12-16 18:56:34

静态方法属于类,而不是对象。 main 方法必须是静态的,因为在执行任何其他代码来实例化任何对象之前首先调用它。它提供了程序的入口点。静态方法是从对象容器外部调用的。静态类变量也是如此。整个类只存在一个副本,这与成员变量不同,成员变量为从类创建的每个对象创建一次。它们用于存储类的数据,例如已创建且未销毁的对象实例的数量。该数据属于该类。静态方法的一个很好的例子是单例模式,其中构造函数是私有的,只能由静态成员函数访问。类外部的函数将无法复制此功能。该方法作用于类数据和对象,因此逻辑上属于同一个类。这一切都归结为封装。一个类只对它自己负责并且只知道它自己。

另一方面,对象方法旨在对与类的单个实例(对象)关联的数据进行操作。构造函数是用于初始化对象并将其数据设置为初始状态的代码。它们在分配内存来存储新对象后立即(自动)执行。即使您没有显式定义构造函数,也会执行一种“默认构造函数”,以便将对象的成员变量和对象的方法代码映射到新对象。

希望这有帮助。

Static methods belong to a class, not an object. The main method must be static because it is called first, before any other code has executed to instantiate any objects. It provides an entry point to the program. Static methods are called from outside of the container of an object. The same is true of static class variables. Only one copy exists for the entire class, as opposed to a member variable, which is created once for each object created from a class. They are used to store data for the class, such as the number of object instances have been created and not destroyed. This data belongs with the class. A good example of a static method is in the singleton pattern, where the constructor is private and can only be accessed by a static member function. A function outside the class would be unable to replicate this functionality. This method acts on class data and objects, so logically belongs to the same class. This all boils down to encapsulation. A class is responsible only for itself and knows only itself.

On the other hand, object methods are meant to operate on the data associated with a single instance of a class, an object. Constructors are the code that is used to initialize an object and set it's data to an initial state. They are executed immediately (and automatically) after the memory has been allocated to store a new object. Even if you do not explicitly define a constructor, a kind of "default constructor" is executed in order to map the object's member variables and the object's method code to the new object.

Hope this helps.

美胚控场 2024-12-16 18:56:34

构造函数用于创建对象。

静态通常是所有对象都相同的。

因此,如果我们有静态构造函数,一个对象的创建将影响所有其他现有对象。

静态方法仅引用静态变量。因此,您为创建对象而提供的所有初始参数都会针对所有对象而更改。创建类似的无用对象是没有意义的。

希望这有帮助......:)

Constructor is used to create Objects.

Static is generally which is same for all objects.

So, if we have had static constructors creation of one object would affect all the other existing objects.

Static methods only reference to static variables. Therefore all the initial parameters which you are giving to create an object would change for all objects. It is no point creating similar objects for no use.

Hope this helps.... :)

狼性发作 2024-12-16 18:56:34

构造函数是对象的属性,而静态与对象无关。这就是为什么没有像静态构造函数这样的东西。但是我们有静态块来完成与构造函数类似的任务,即字段的初始化等。

Constructor is the property of an object while static has nothing to do with object. That's why there is nothing like static constructor. But we have static block to do the similar task as constructor i.e. initialization of fields etc.

雪化雨蝶 2024-12-16 18:56:34

Bruce Eckel 所著的《Thinking In Java》第 4 版第 272 页上写道:

²即使 static 关键字不显式,构造函数也是静态方法。因此,准确地说,当访问类的任何静态成员时,首先加载该类。

更多背景信息。

...每个类的编译代码都存在于其自己的单独文件中。直到需要代码时才会加载该文件。一般来说,您可以说“类代码在首次使用时加载”。这通常是在构造该类的第一个对象时发生,但在访问静态字段或静态方法时也会发生加载。²

如果您考虑一下静态方法不能的规则,那么这很有意义使用同一类的非静态方法。几周前,当我无法理解如何使用单例模式访问用于创建该类的新实例的静态方法内的构造函数时,我就有了这个疑问。今天翻这本书,看到这样的解释。

从某种意义上说,如果构造函数不是静态的,您首先需要该类的实例才能访问它,但我想这可能会引发关于先有鸡还是先有蛋的旧讨论。

希望有帮助!

On page 272 of Thinking In Java, 4th Edition, by Bruce Eckel, it says:

²The constructor is also a static method even though the static keyword is not explicit. So to be precise, a class is first loaded when any of its static members is accessed.

A little bit more context.

... the compiled code for each class exists in its own separate file. That file isn't loaded until the code is needed. In general you can say "class code is loaded at the point of first use." This is usually when the first object of that class is constructed, but loading also occurs when a static field or static method is accessed.²

This makes a lot of sense, if you think about the rule that says that a static method can't use non-static methods of the same class. I had this doubt a couple weeks ago when I couldn't understand how, using the Singleton Pattern, you could access the constructor inside the static method that is used to create a new instance of that class. Today I was flipping through the book and I came across this explanation.

It also makes sense in a way that, if the constructor wasn't static, you'd first need an instance of that class to be able to access it, but I guess this could spark up the old discussion about the chicken or the egg.

Hope it helped!

不回头走下去 2024-12-16 18:56:34

构造函数既不是完全静态的(类级别),也不是完全非静态的(实例级别)。

  • 与实例方法不同,构造函数不是继承的。
  • 与静态方法不同,构造函数可以引用 this

那么,为什么不能声明构造函数static呢?

好吧,我的看法是,(冗余的)static 关键字会令人困惑,并且不会起到任何作用。因此他们决定不允许这样做。


静态初始化块可以被视为构造函数的解释在概念上是错误的(IMO)。 (这类似于说实例初始化块是常规构造函数。这同样是错误的。)

静态初始化和构造之间的主要区别1是:

  • 静态初始化发生在不确定的时间 2;对于类初始化,没有与 new 等效的方法,
  • 没有直接的方法将(构造函数)参数传递给初始化代码,
  • 没有实用的方法可以从静态初始化期间发生的错误中恢复。

1 - 假设,如果类初始化是显式的,那么使用静态构造函数是有意义的。但缩小规模是应用程序需要显式地“构造”它们使用的所有类......这将是可怕的。

2 - 如果动态加载类,您就有一定程度的控制权,但即使这样,如果该类已经在当前类加载器中加载并初始化,那么尝试控制初始化将会失败。


我不明白为什么 main 方法必须是静态的。

如果您希望 main 方法充当应用程序的入口点,则必须如此。

问题是,如果 main 是一个实例方法,那么就需要有一个入口点类的实例来调用 main 方法。但如何创建它呢?您会选择哪个构造函数?如果没有公共构造函数怎么办?

底线是,这就是 Java 的设计方式……早在 20 世纪 90 年代……到目前为止,他们还没有看到需要改变这一点。


Constructors are neither entirely static (class level) or entirely non-static (instance level).

  • Unlike instance methods, constructors are not inherited.
  • Unlike static methods, a constructor can refer to this.

So, why can't you declare a constructor static?

Well, my take is that a (redundant) static keyword would be confusing and would not serve any purpose. Therefore they decided not to allow it.


The explanation that static initialization blocks can be viewed as constructors is (IMO) conceptually wrong. (It is analogous to saying that an instance initialization block is a regular constructor. Which is equally wrong.)

The key distinctions between static initialization and construction1 are:

  • static initialization happens at an indeterminate time2; there is no equivalent to new for class initialization,
  • there is no straight-forward way to pass (constructor) parameters to the initialization code
  • there is no practical way to recover from errors occurring during static initialization.

1 - Hypothetically, if class initialization was explicit, then it would make sense to have static constructors. But the downsize would be that applications would need to explicitly "construct" all of the classes that they used ... which would be horrible.

2 - You have a degree of control if you load a class dynamically, but even then if the class has already been loaded and initialized in the current classloader, then attempting to control initialization will fail.


I do not understand why the main method has to be static.

It has to be if you want the main method to act as an entrypoint for your application.

The problem is that if main was an instance method, then there would need to be an instance of your entrypoint class to call the main method on. But how do you create it? Which constructor would you choose? What if there was no public constructor?

The bottom line is that this is the way that Java was designed ... back in the 1990's ... and so far they have not seen the need to change this.


一萌ing 2024-12-16 18:56:34

a) static 属于类而不是对象,并且在对象创建期间调用 constrictor。
b)如果我们创建一个静态构造函数,那么它不能被子类调用,因为静态只能从类访问,而不能由子类访问。因此,在子类对象创建过程中,不能调用当前类的构造函数。
c) 静态成员在程序中首先执行,因此如果我们将构造函数声明为静态,那么它将在对象创建之前执行,这与构造函数的目的相反。

如果我们将构造函数声明为静态,那么它将给出编译时错误。
如果我们想初始化静态成员,那么需要使用静态块。

a) static is belongs to class not object and constrictor is called during the object creation.
b) if we create a constructor as static then it can't be call by subclass as static is accessible only from class not by sub class. So during subclass object creation it can't be call the present class constructor.
c) static members are executed first in the program, so if we declare constructor as static then it will executed before object creation which is oppose the purpose of the constructor.

If we declare constructor as static then it will give compile time error.
If we want to initialize static member then need to use of static block.

ㄟ。诗瑗 2024-12-16 18:56:34

我昨天写了一个简单的例子作为相关问题的答案,这可能有助于使事情更容易理解: java 构造函数的意义是什么?

静态方法的意义在于,无需创建类的实例即可调用它们,而“普通”实例方法与实例,没有实例就无法调用。

由于Main类的Main方法是程序的入口点,不可能还没有创建实例,所以自然不能通过实例访问它。因此,它是静态的,因此可以作为程序的启动来运行。

I wrote a simple example as an answer to a related question yesterday which may help make things more understandable: what's the point of java constructor?

The point of Static methods is that they can be called without creating an instance of a class, while "normal" instance methods are related to an instance, and can not be called without one.

Since the Main method of the Main class is the entry point of the program, no instance can possibly have been created yet, so naturally, you can not access it via an instance. Therefore, it is Static, so it can be run as the start of the program.

假装爱人 2024-12-16 18:56:34

只要看一下这个链接,它肯定会帮助您理解:
为什么不能创建构造函数静态?

AND

当我们创建对象时,构造函数在运行时被调用。
静态对于所有对象都是相同的,但所有对象都有自己的状态和属性。
因此,如果我们有静态构造函数,一个对象的创建将影响所有其他现有对象。
注意:静态是类级别的,而构造函数与对象相关。

例如,

  public class Foo
    {
       String name;
       int id;
        // define constructors
           Foo (String name, int id)
        {
            this.name = name;
            this.id = id;
        }

          p s v m(String[] arg)
      {
          Foo f1 = new Foo("Amit",001);
          Foo f2 = new Foo("Rahul",002);
      }
    }

如果我们创建静态构造函数,那么两个对象(f1 也)将包含有关 name 和 id 的最后更新值,如 Rahul 和 002。

Just take a look on this link, it will definately help you to understand:
Why can't make a constructor static?

AND

Constructor is called at Run-time when we create Objects.
Static is same for all objects but all objects have their own state and properties.
So, if we have had static constructors creation of one object would affect all the other existing objects.
Note: static is class level while constructors related to the objects.

e.g.

  public class Foo
    {
       String name;
       int id;
        // define constructors
           Foo (String name, int id)
        {
            this.name = name;
            this.id = id;
        }

          p s v m(String[] arg)
      {
          Foo f1 = new Foo("Amit",001);
          Foo f2 = new Foo("Rahul",002);
      }
    }

If we create static constructor then both objects(f1 also) will contain the last updated value regarding name and id as Rahul and 002.

吲‖鸣 2024-12-16 18:56:34

构造函数不能是静态的,因为在 OO 语言中,创建对象的过程如下:

  • 分配对象
  • 调用构造函数来初始化新分配的对象

构造函数不会在其他任何地方使用(并且类型安全语言应该强制执行) this),因此构造函数将始终在非静态上下文中调用。

如果构造函数是静态的,它将不会接收对新分配的对象的引用,因此无法初始化它。

因此,构造函数始终可以是非静态的(因为它始终从非静态上下文中调用)并且必须始终是非静态的(否则它将无法执行其任务)。

A constructor cannot be static, because in an OO language, the process for creating an object is as follows:

  • allocate the object
  • call the constructor to initialise the newly-allocated object

Constructors are not used anywhere else (and a type-safe language should enforce this), so it follows that a constructor will always be called in a non-static context.

If a constructor were static, it would not receive a reference to the newly-allocated object, and thus would not be able to initialise it.

Thus, a constructor can always be non-static (as it is always called from a non-static context) and must always be non-static (otherwise it would be unable to perform its task).

○闲身 2024-12-16 18:56:34

main(String[]) 方法有一个特定的原型,该原型由 Java 运行时环境的工作方式决定。当您从命令行调用 java MyApplication 时,Java VM 将查找该类中包含的静态 main(String[]) 方法,以便执行应用程序。如果找不到该方法,则 Java VM 无法将该类作为应用程序运行。这就是语言的定义方式。这也意味着 Java VM 不会创建应用程序类的实例来运行它。

现在,如果您希望您的类可用作独立应用程序或作为由其他应用程序创建的实例,那么您可以让您的类实现 Runnable 接口,并提供 main 方法,在新实例上执行 run 方法。

public class MyRunnableThing implements Runnable
{
    // Define whatever variables your runnable thing needs here as
    // private instance fields.

    /** Fulfills requirements of Runnable interface. */
    public void run()
    {
        System.out.println( "I'm running..." ) ;
    }

    /** Also makes the class runnable from the console. */
    public static void main( String[] args )
    {
        MyRunnableThing runMeNow = new MyRunnableThing() ;
        runMeNow.run() ;
    }
}

现在,任何类都可能创建 MyRunnableThing 的实例,并使用其 run() 方法来产生相同的行为通过执行 java MyRunnablething 可以看到这一点。

另请参阅:在 Java 中使用静态构造函数。该问答的一些亮点:

  • 构造函数用于创建类的实例,因此它是实例方法,而不是静态方法。
  • 您可以创建一个静态方法,使用构造函数创建该类的实例。这就是流行的新“构建者”课程的工作原理。
  • 您可以创建一个返回持久、唯一的单例实例的静态方法。
  • 如果您的类具有静态成员,那么您可以创建一个静态初始化器来初始化这些成员的值。

The main(String[]) method has a specific prototype that is dictated by how the Java runtime environment works. When you invoke java MyApplication from the command line, the Java VM will look for a static main(String[]) method contained in that class in order to execute the application. If that method is not found, then the Java VM can't run the class as an application. That's just how the language is defined. It also means that the Java VM doesn't create an instance of your application class in order to run it.

Now, if you want your class to be usable either as a standalone application or as an instance that's created by something else, then you can have your class implement the Runnable interface, and also provide a main method that executes the run method on a new instance.

public class MyRunnableThing implements Runnable
{
    // Define whatever variables your runnable thing needs here as
    // private instance fields.

    /** Fulfills requirements of Runnable interface. */
    public void run()
    {
        System.out.println( "I'm running..." ) ;
    }

    /** Also makes the class runnable from the console. */
    public static void main( String[] args )
    {
        MyRunnableThing runMeNow = new MyRunnableThing() ;
        runMeNow.run() ;
    }
}

Now any class could potentially create an instance of MyRunnableThing and use its run() method to produce the same behavior that would have been seen by executing java MyRunnablething.

See also: Working with Static Constructor in Java. Some highlights from that Q&A:

  • A constructor is used to create an instance of the class, so it's an instance method, not a static method.
  • You can create a static method that creates an instance of the class, using the constructor. This is how the trendy new "builder" classes work.
  • You can create a static method that returns a persistent, unique singleton instance.
  • If your class has static members, then you can create a static initializer to initialize the values of those members.
沩ん囻菔务 2024-12-16 18:56:34

构造函数的目的是构造一个对象,即用默认值或初始化值来初始化类的实例变量。非静态实例变量不能通过静态方法访问。所以构造函数不是静态的。

The purpose of Constructor is to Construct an Object i.e. to initialize class's instance variables either their default values or by their initialized values. non-static Instance variables can't be accessed by static methods . So constructor is not static.

青丝拂面 2024-12-16 18:56:34

声明为静态的方法不需要创建对象。由于我们不为 main 方法创建对象,因此将其声明为静态。

隐式调用构造函数来初始化对象,因此使用静态构造函数没有任何意义。

The method declared as static requires no object creation .As we don't create object for the main method it is declared as static.

constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.

七色彩虹 2024-12-16 18:56:34

首先,关键字static意味着所有标记为static的东西都必须是类级别的东西,并且只属于类。而构造函数属于对象,通常在我们使用时会调用它们new 运算符。所以我们现在知道构造函数甚至不是类属性,我们怎么可能将其标记为静态呢?

第二,静态构造函数违反了java继承的全部目的。每次创建子类对象之前,JVM都会自动调用超类构造函数,为创建子类对象做好准备。我们将构造函数标记为静态,子类将无法访问其超类的构造函数,因为它被标记为静态,因此仅属于类。

First, the key word static means that everything marked static must be the class-level thing and belongs to the class only.While constructors belong to object and they may usually be called when we use the new operator.So we now know that a constructor is not even a class property,how could we possibly mark it as static?

Second,static constructor violates the whole purpose of inheritance in java.Every time just before we create an subclass object ,JVM automatically calls the superclass constructor to make it ready for the subclass object to be created.But if we mark the constructor static,the subclass will not be able to access the constructor of its superclass because it's marked static thus belongs to class only.

残疾 2024-12-16 18:56:34

Java 不允许将构造函数声明为静态。原因如下。

  1. 静态意味着同一个类。即静态方法不能被继承。

  2. 对于静态,不能使用“this”引用(关键字)。 “this”总是链接到一个对象。构造函数总是属于某个对象。

  3. 如果构造函数是静态的,则子类的对象无法访问。如果构造函数允许静态,则可以在类内访问它,但不能由子类访问。

Java does not permit to declare a constructor as static. Following are the reasons.

  1. Static means for the same class. i.e, static methods cannot be inherited.

  2. With static, "this" reference (keyword) cannot be used. "this" is always linked to an object. A constructor always belongs to some object.

  3. If a constructor is static, an object of subclass cannot access. If static is allowed with constructor, it is accessible within the class but not by subclass.

私野 2024-12-16 18:56:34

静态属于类,构造函数属于对象

我们知道静态方法、块或变量属于类。而构造函数属于对象,当我们使用 new 运算符创建实例时会被调用。由于构造函数不是类属性,因此不允许它是静态的是有道理的。

Static Belongs to Class, Constructor to Object

We know that static methods, block or variables belong to the class. Whereas a Constructor belongs to the object and called when we use the new operator to create an instance. Since a constructor is not class property, it makes sense that it’s not allowed to be static.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文