如何控制Java中变量的可见性? [英] How to control visibility of variables in Java?

查看:332
本文介绍了如何控制Java中变量的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以想象3种类型的变量可见性(但我认为还有更多):

I can imagine 3 type of visibility for variables (but I think there are more):


  1. 变量用于方法和该变量值的任何变化都不能从方法外部看到(因此它对于特定方法是局部的)。

  1. Variable is used within a method and any changes of the value of this variable are not visible from outside of the method (so it is local for a particular method).

变量这是班级的本地意义,这意味着从班级的外部来看它是不可见的。但是,类的任何方法都可以轻松查看和更改此变量的值,而无需在方法的参数列表中提供变量(因此它在类中是全局的)。

A variable is local to the class meaning that it is unvisible from outisde of the class. However, any method of the class can easily see and change value of this variable without necessity to give the variable in the list of arguments of methods (so it is kind of global within the class).

变量可以通过objectName.variableName访问。

Variable can be accessed by "objectName.variableName".

我如何声明这些不同类型的变量?

How do I declare these different kinds of variables?

推荐答案

1)方法中声明的任何变量只在该方法中可见。 (方法本地)。程序员别无选择。

1) Any variable declared in a method is only visible in that method. (method-local). The programmer has no choice in that.

2)使用修饰符 private 声明的任何变量只能从内部看到它被延迟的类的实例。

2) Any variable declared with the modifier private is visible only from within instances of the class it is delared in.

3) public 可以从任何具有对象的类访问变量。变量; protected 变量只能从子类以这种方式访问​​; private 变量只能在声明变量的类的实例中以这种方式访问​​。

3) public variables can be accessed from any class with object.variable; protected variables can be accessed in this way from subclasses only; private variables can be accesses in this way only within instances of the class the variable is declared in.

详细信息和参考,请参阅Sun网站上的 Java Learning Trail

For detail and reference, see the Java Learning Trail on Sun's website.

但是:将类成员(变量)暴露给其他类是不好的做法,应该使用方法启用访问,例如:

However: exposing class members (variables) to other classes is bad practise, and access should be enabled using methods, such as:

public class MyClass {
  private int myInt;

  public int getMyInt() {
    return myInt;
  }

  public void setMyInt(int newInt) {
    myInt = newInt;
  }
}

这篇关于如何控制Java中变量的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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