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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With