What is the difference between a local variable, an instance field, an input parameter, and a class field?
A local variable is defined within the scope of a block. It cannot be used outside of that block.
Example:
if(x > 10) {
String local = "Local value";
}
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.
If I wanted to use it outside of the object, and it was not public
, I would have to use getters and/or setters.
Example:
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.
Example:
public class Point {
private int xValue;
public Point(int x) {
xValue = x;
}
public void setX(int x) {
xValue = 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.
Example:
System.out.println(Integer.MAX_VALUE);
I don't need an instance of Integer
to retrieve the globally known maximum value of all ints.
Not quite.
A class field is what you think a local variable is but it is generally a static field and so is the same across all instances.
An instance field is the same as a class field, but is non static and can be different for each instance of the object.
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
And a local variable is a variable inside a method or block, that can only be used by that method or block.
Oh and your input parameter definition is correct, an input parameter is a field that is passed to a method as a parameter.
A class field is often called a class variable, and you can find that information here