Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

java - What is the difference between a local variable, an instance field, an input parameter, and a class field?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...