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

后端 未结 6 1555
借酒劲吻你
借酒劲吻你 2020-12-11 07:26
class Employee {    
    int DOB;
    int eid;
    String name;
    double salary;
    System.out.println(\"Employee class\");
}

If I write the

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 08:05

    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.

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

    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:

    • http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

提交回复
热议问题