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

后端 未结 6 1534
借酒劲吻你
借酒劲吻你 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:16

    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. 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.

提交回复
热议问题