局部变量、实例字段、输入参数和类字段有什么区别? [英] 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";
}
我不能在 if
块之外使用 local
.
I cannot use local
outside of that if
block.
实例字段,或字段,是绑定到对象本身的变量.我可以在对象中使用它而不需要使用访问器,并且对象中包含的任何方法都可以使用它.
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);
我不需要 Integer
的实例来检索所有整数的全局已知最大值.
I don't need an instance of Integer
to retrieve the globally known maximum value of all ints.
这篇关于局部变量、实例字段、输入参数和类字段有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!