简体   繁体   English

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

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

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

If I write the System.out.println inside a method,it seems to work. 如果我在方法中编写System.out.println ,它似乎工作。 But not when written directly inside a class. 但不是直接在课堂上写的。 Why is a method necessary? 为什么需要一种方法?

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 class per-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()不是字段声明,因此不允许。

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 Static blocks and Instance blocks. 您可以使用其他块,例如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 Runtime系统将保证它们按照它们在您的类中出现的顺序执行

See also: 也可以看看:

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. 正确地写你的信息。

This is other way around called as initializer block. 这是另一种称为初始化块的方法。 This will print "Employee class" everytime you create new Employee 每次创建new Employee都会打印"Employee class"

class Employee {

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

}

about your question 关于你的问题

Why does System.out.println have to be inside a method? 为什么System.out.println必须在方法内?

Java compiler is designed so to restrict such calls. Java编译器旨在限制此类调用。
This is not only for System.out.println but is applicable for any method you call from the class. 这不仅适用于System.out.println而且适用于您从该类调用的任何方法。
Try calling MySystem.myout.myprintln(); 尝试调用MySystem.myout.myprintln(); //remember create such classes in advance. //记得提前创建这样的类。
Try calling your own class' method. 尝试调用自己的类方法。

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. 不要将Java类视为按顺序执行的内容,读入每一行。将Class视为一种奇特的工具。 Like 喜欢

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()放在这些工具之一之外,你就不知道它何时会发生,或者它会发生什么,或者它是什么工具。

The System class contains several useful class fields and methods. System类包含几个有用的类字段和方法。 It cannot be instantiated. 它无法实例化。

Among the facilities provided by the System class are standard input, standard output, and error output streams; System类提供的功能包括标准输入,标准输出和错误输出流; 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. 以及用于快速复制阵列的一部分的实用方法。

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 您不能只在方法之外运行代码,除非它是变量/常量声明,类声明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么`System.out.println(null);`give“方法println(char [])对于类型PrintStream错误是不明确的”? - Why does `System.out.println(null);` give “The method println(char[]) is ambiguous for the type PrintStream error”? System.out.println()在Java中是否有副作用? - Does System.out.println() have a side effect in Java? 为什么Java中的记录器很少像System.out.println那样具有.toString()? - Why do loggers in Java rarely have the .toString() that System.out.println does? 为什么 System.out.println(&#39;a&#39; == 97.0) 给出 true - Why does System.out.println('a' == 97.0) give true 为什么 System.out.println(“0:00”.compareTo(“0”)); 结果是3? - Why does System.out.println(“0:00”.compareTo(“0”)); result in 3? 为什么 Java 中的 System.out.println() 会打印到控制台? - Why does System.out.println() in Java print to the console? 为什么/什么时候 System.out.println(); 给出错误:方法打印(布尔)...不适用 - Why/when does System.out.println(); give error: method print(boolean)...not applicable 在 Java 中,为什么 System.out.println(“\\” \\\\“); 给出“\\”作为输出 - In Java, why does System.out.println(“\” \\“); gives ” \ as output 为什么System.out.println()以ASCII码零终止 - Why does System.out.println() terminate at ASCII Code zero 为什么Java中的System.out.println(-1 &lt;&lt; 32)= - 1? - Why does System.out.println(-1<<32)=-1 in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM