java 为什么 System.out.println 必须在方法内部?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15901973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:13:55  来源:igfitidea点击:

Why does System.out.println have to be inside a method?

java

提问by user2261650

class Employee {    
    int DOB;
    int eid;
    String name;
    double salary;
    System.out.println("Employee class");
}

If I write the System.out.printlninside a method,it seems to work. But not when written directly inside a class. Why is a method necessary?

如果我在System.out.println里面写一个方法,它似乎有效。但当直接在类中编写时则不然。为什么需要一个方法?

回答by Michael Berry

It's the same as any other code that gets executed - it has to be inside a method! (Yes, ish, for the purists, I'm also including constructors and static / instance initialiser blocks.) Think about it - if it wasn't inside a method or other related code block as you propose, then when would that code get executed? It wouldn't make much sense. You can't execute a classper-se, you can only execute a specific method / constructor / etc. contained within that class.

它与执行的任何其他代码相同 - 它必须在方法内部!(是的,是的,对于纯粹主义者,我还包括构造函数和静态/实例初始化块。)考虑一下 - 如果它不在您建议的方法或其他相关代码块中,那么该代码何时会得到被执行?这没有多大意义。您本身不能执行类,只能执行该类中包含的特定方法/构造函数等。

The only things allowed outside method and constructor declarations are declarations of fields. Since System.out.println()is not a field declaration, it's not allowed.

在方法和构造函数声明之外唯一允许的事情是字段声明。由于System.out.println()不是字段声明,因此不允许。

回答by Rodrigo Sasaki

It needs to be inside an executable block of code to be executed. Otherwise there's no way to know when to execute it.

它需要位于要执行的可执行代码块内。否则没有办法知道什么时候执行它。

It doesn't have to be a method. You can use other blocks, such as Staticblocks and Instanceblocks.

它不一定是一种方法。您可以使用其他块,例如Static块和Instance块。

For example, if you want a code to be executed whenever the class is loaded by the ClassLoader, you can use a static block:

例如,如果您希望在 ClassLoader 加载类时执行代码,则可以使用静态块:

public class MyClass{
    static{
        System.out.println("MyClass loaded");
    }
}

If you want a code to be executed whenever a new instance of that class is created, you can use and instance block:

如果您希望在创建该类的新实例时执行代码,您可以使用和实例块:

public class MyClass{
    {
        System.out.println("New instance of MyClass created");
    }
}

It's important to say that you can have as many of these blocks as you need, and they can appear anywhere in the class body. The Runtime system will guarantee that they are executed in the order that they appear in your class

重要的是,您可以根据需要拥有尽可能多的这些块,并且它们可以出现在类主体中的任何位置。运行时系统将保证它们按照它们在类中出现的顺序执行

See also:

也可以看看:

回答by Milo? Luka?ka

when it would be inside a class, but outside of any method, you cannot call it, you have to create method for example getData() and calling

当它在一个类内,但在任何方法之外时,你不能调用它,你必须创建方法,例如 getData() 并调用

Employee e = new Employee().getData();

properly writes your message.

正确地写下您的信息。

回答by AmitG

This is other way around called as initializer block. This will print "Employee class"everytime you create new Employee

这是另一种称为初始化程序块的方式。这将在"Employee class"您每次创建时打印new Employee

class Employee {

    int DOB;
    int eid;
    String name;
    double salary;
    {
        System.out.println("Employee class");   
    }

}

about your question

关于你的问题

Why does System.out.printlnhave to be inside a method?

为什么System.out.println必须在方法内部?

Java compiler is designed so to restrict such calls.
This is not only for System.out.printlnbut is applicable for any method you call from the class.
Try calling MySystem.myout.myprintln();//remember create such classes in advance.
Try calling your own class' method.

Java 编译器旨在限制此类调用。
这不仅System.out.println适用于而且适用于您从类中调用的任何方法。
尝试调用MySystem.myout.myprintln();//remember 提前创建此类类。
尝试调用您自己的类的方法。

回答by durron597

Don't think about a Java class as something that gets executed in order, every line is read in. Think about a Class as a fancy tool. Like

不要将 Java 类视为按顺序执行的东西,每一行都被读入。将类视为一种奇特的工具。喜欢

public class Bathtub {
    private int waterLevel;

    public void drain() {
        waterLevel = 0;
    }

    public void fill(int newWater) {
        waterLevel += newWater;
    }

    public void playWithDuckies() {
        System.out.println("Whee this is fun!!");
    }
}

Each method is something you can do with the Bathtub. Think about Swiss-Army-Knife, you have the scissors, the knife, the tweezers, the corkscrew. Each one does a purpose when you call it.

每种方法都是您可以用浴缸做的事情。想想瑞士军刀,你有剪刀、小刀、镊子和开瓶器。当你调用它时,每一个都有一个目的。

If you put System.out.println()outside one of these tools, you don't know when it would happen or what would make it happen or what tool it's a part of.

如果您将System.out.println()这些工具中的一个放在外面,您将不知道它何时会发生或会发生什么,或者它是什么工具的一部分。

回答by Raghunandan

The System class contains several useful class fields and methods. It cannot be instantiated.

System 类包含几个有用的类字段和方法。它不能被实例化。

Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

System 类提供的工具包括标准输入、标准输出和错误输出流;访问外部定义的属性和环境变量;一种加载文件和库的方法;以及一种用于快速复制数组一部分的实用方法。

out is the standard output stream and println is the method.

out 是标准输出流, println 是方法。

You can't just run code outside of a method unless it's a variable/constant declaration, a class declaration

你不能只在方法之外运行代码,除非它是一个变量/常量声明,一个类声明