Why can't static classes have non-static methods and variables?

前端 未结 3 1345
小蘑菇
小蘑菇 2020-12-15 10:10

Why can\'t static classes have non-static methods and variables when non-static classes can have static methods and variables?

What is the advantage of having static

3条回答
  •  执笔经年
    2020-12-15 10:42

    Say you have a class Person that has a field name. And let's suppose, for the sake of argument, that Java did allow static methods to directly access non-static member variables. We might then specify a getName static method for our Person like so:

    class Person {
      private final String name;
    
      public Person(String name) {
        this.name = name;
      }
    
      public static String getName() {
        return name;
      }
    }
    

    Now let's try using this class in an example:

    public static void main(String[] args) {
      Person alice = new Person("Alice");
      Person bob = new Person("Bob");
      System.out.println("name: " + Person.getName());
    }
    

    So tell me, what on earth would we expect Person.getName() to print in this example? Alice? Bob? Null?

    There's no right answer. It makes no sense, because a name is something that belongs to an individual (an instance), not the class as a whole. So clearly we cannot have a static method access non-static members because we have no way of knowing which non-static members we should be accessing.

提交回复
热议问题