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

前端 未结 3 1341
小蘑菇
小蘑菇 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:29

    Static class can't contain non-static members because by definition it can't be instantiated so there's no possibility to use these members.

    However, static members in non-static class can be used without having class instance - a bit different scenario, i.e. for utility methods or factory methods.

    0 讨论(0)
  • 2020-12-15 10:33

    Static classes can't be instantiated in the first place, so even if you could declare non-static (instance) members, they can never be accessed. Since there really isn't a point allowing it for that reason, the language simply prohibits it.

    Bear in mind that static classes are just the classes, while there are two things that are directly related to non-static classes: the classes themselves, and the instances/objects of the classes.

    A non-static class can have both static and non-static members so that the static members apply to the class, whereas the non-static members apply to the instances of that class.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题