局部变量,实例字段,输入参数和类字段之间有什么区别? [英] What is the difference between a local variable, an instance field, an input parameter, and a class field?
问题描述
关于简单Java程序的局部变量,实例字段,输入参数和类字段有什么区别?
What is the difference between a local variable, an instance field, an input parameter, and a class field with respect to a simple Java program?
推荐答案
局部变量是在块的范围内定义的。它不能在该区块之外使用。
A local variable is defined within the scope of a block. It cannot be used outside of that block.
示例:
if(x > 10) {
String local = "Local value";
}
我不能使用本地
之外
阻止。
实例字段或 field ,是一个绑定到对象本身的变量。我可以在对象中使用它而无需使用访问器,对象中包含的任何方法都可以使用它。
An instance field, or field, is a variable that's bound to the object itself. I can use it in the object without the need to use accessors, and any method contained within the object may use it.
如果我想在外面使用它对象的,它不是 public
,我必须使用getter和/或setter。
If I wanted to use it outside of the object, and it was not public
, I would have to use getters and/or setters.
示例:
public class Point {
private int xValue; // xValue is a field
public void showX() {
System.out.println("X is: " + xValue);
}
}
输入参数,或参数,甚至参数,是我们传递给方法或构造函数的东西。它具有关于我们传递给它的方法或构造函数的范围。
An input parameter, or parameter or even argument, is something that we pass into a method or constructor. It has scope with respect to the method or constructor that we pass it into.
示例:
public class Point {
private int xValue;
public Point(int x) {
xValue = x;
}
public void setX(int x) {
xValue = x;
}
}
两者 x
参数绑定到不同的范围。
Both x
parameters are bound to different scopes.
类字段或静态字段类似到一个字段,但区别在于你不需要有一个包含对象的实例来使用它。
A class field, or static field, is similar to a field, but the difference is that you do not need to have an instance of the containing object to use it.
示例:
System.out.println(Integer.MAX_VALUE);
我不需要整数
检索所有整数的全局已知最大值。
I don't need an instance of Integer
to retrieve the globally known maximum value of all ints.
这篇关于局部变量,实例字段,输入参数和类字段之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!