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

查看:130
本文介绍了为什么System.out.println必须在方法内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如果我写 System.out.println 在一个方法里面,它似乎工作。但不是直接写在一个类中。为什么是一个方法需要

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

推荐答案

这是一样的被执行任何其他代码 - 它必须是一个方法里面! (是的,ISH,对于较真的,我还包括构造函数和静态/实例初始化器块。)想想看 - 如果它不是一个方法或者你提出其他相关的代码块内,那么当将这些代码得到执行?这没有多大意义。你不能执行一个类本身,你只能执行该类中包含的特定方法/构造函数等。

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.

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆