Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

java - 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. But not when written directly inside a class. Why is a method necessary?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...