what is difference between declaring variable out of main method and inside main method?

前端 未结 6 714
我在风中等你
我在风中等你 2021-01-31 22:36

When I was reading book about Java , I saw one example written like this. And I am wondering can I declare variable in outside of main method ? What is difference between declar

6条回答
  •  Happy的楠姐
    2021-01-31 22:40

    1) Inside vs Outside:

    If you declare your object inside a method, it will be visible only in this method. Basically, if you put brackets around it, it's only visible/accessible from within these brackets.

    If you declare your object outside the method (inside the class), it depends on the access modifier.
    By default, it's visible/accessible from within that class and the whole package.

    2) Static

    Static means, that this Object/Variable belongs to the class itself, and not to its objects.

    Example:

    public class Members {
    
      static int memberCount;
    
      public Members() {
         memberCount++;
      }
    }
    

    memberCount exists only once, no matter how many Objects of the class exists. (even before any object is created!)

    Every time you create a new Object of Members, memberCount is increased. Now you can access it like this: Members.memberCount

提交回复
热议问题