简体   繁体   中英

Can't access a class's public field

EDIT: I've modified this question in response to some of the comments/answers. I'm printing out the object field, but it still breaks. At this point, I'm guess the javarepl's fault.

I'm new to Java so apologies for the very basic question. I'm playing around with Java in the javarepl.

     class SomeKlass {
        public int someField;

        public SomeKlass(int inputField) {
         someField = inputField;
        }
      }

      SomeKlass someObj = new SomeKlass(1);

      System.out.println(someObj.someField)

      ERROR: cannot find symbol
      symbol:   variable someField
      location: variable someObj of type java.lang.Object
      System.out.println(someObj.someField);

How come I can't access someField even though I declared it as a public field of SomeKlass ?

The error message "ERROR: not a statement" indicates the problem, the someObj.someField is a variable and the repl doesn't know what you want to do with that variable. If you want to print it, you can do so like

System.out.println(someObj.someField);

You should access it no problem, although it is bad practice to expose your fields. Getters, and Setters would be more appropriate. If you make a main method you should be able to run it.

class App {
    public static void main(String[] args) {
        SomeKlass someObj = new SomeKlass(1);
        System.out.println(someObj.someField);
    }
}

Now the correct way to do it, is with a getter and setter. In your class:

private someField;

public int getSomeField(){
    return someField;
}

public int setSomeField(int someFieldInput){
    someField = someFieldInput;
}

Since you are using javarepl I am sharing my ans specifically on it, If you want to print the variable value using javarepl you can do something like this new SomeKlass(1).someField; 在此输入图像描述 I have not use javarepl till now, but its better if you use some IDE like Eclipse.

First of all, assuming this is the exact code you have written, then I can advise that you need to perform accessing any variable in a declared method, ie main method or something.

Secondly, you cannot just acccess some field and leave it there without assigning something to it or not assigning it to something. So, someObj.someField; is not a correct Java syntax.

The example below will help you.

public class SomeKlass {
    public int someField;

    public SomeKlass(int inputField) {
     someField = inputField;
    }
    public static void main(String[] args) {

        SomeKlass someObj = new SomeKlass(1);

        someObj.someField = 1;      // Assign something to it.
        int i = someObj.someField;  //Assign it to something.
        System.out.println(i);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM