声明变量的主方法和内部主方法有什么区别? [英] what is difference between declaring variable out of main method and inside main method?

查看:173
本文介绍了声明变量的主方法和内部主方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读有关Java的书时,我看到了一个这样写的例子。我想知道我可以在main方法之外声明变量吗?声明变量外部和内部主方法有什么区别?什么是静态在这里的作用?请有人向我解释一下?我是java的新手。

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 declaring variable outside and inside main method? what is " static" 's role in here ? Please some one explain to me? I am new in java.

public class Printstuff {
      static int an_integer = 0;
        public static void main(String[] args) {
          int an_integer = 2;
          String[] some_strings = {"Shoes", "Suit", "Tie" };
          an_integer = an_integer - 1;
          some_strings[an_integer] = some_strings[an_integer] +"+++";
          for (int i = 0; i < some_strings.length; i++)
            System.out.println(some_strings[Printstuff.an_integer]);
        }
    }

祝你好运。

推荐答案

1)内部与外部:

如果声明对象里面一个方法,它只在这个方法中可见。基本上,如果你在它周围放置括号,它只能在这些括号内可见/可访问。

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 means, that this Object/Variable belongs to the class itself, and not to its objects.

示例:

public class Members {

  static int memberCount;

  public Members() {
     memberCount++;
  }
}

memberCount 只存在一次,无论该类存在多少个对象。 (甚至在创建任何对象之前!)

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

每次创建成员的新对象时, memberCount 增加了。现在您可以这样访问它: Members.memberCount

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

这篇关于声明变量的主方法和内部主方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆