问题
I have a class with some variables. When I instantiate an object of that class in the main class. I can only access and modify member variables in a method, any method; not outside them. Why is that? I am stuck and can't seem to find an answer on google.
class SomeVariables{
String s;
int dontneed;
}
class MainClass{
SomeVariables vars= new SomeVariables();
vars.s = "why this doesnt work?. IDE says Uknown class 'vars.s'";
System.out.println(vars.s); // Accesing it also doesnt work
void ChangeValue(){
vars.s = "why does this work?";
}
public static void main(String[]args){
}
}
Also I tried access specifiers and got the same result
回答1:
It does not work because you are defining the instances outside of a constructor or methos which is not valid Java syntax.
A possible fix would be:
class SomeVariables {
String s;
int dontneed;
}
class MainClass {
public static void main(String[]args){
SomeVariables vars = new SomeVariables();
vars.s = "why this doesnt work?. IDE says Uknown class 'vars.s'";
System.out.println(vars.s);
}
}
But you might want to consider protection of your class variables such are making all attributes og the SomeVariables
and use setters
and getters
methods to get and modify the value in the class itself. For example:
class SomeVariables {
private String s;
private int dontneed;
// Constructor method
public SomeVariables() {
// Initialize your attributes
}
public String getValue() {
return s;
}
public void setValue(String value) {
s = value;
}
}
class MainClass {
public static void main(String[]args){
SomeVariables vars = new SomeVariables();
vars.setValue("Some value");
System.out.println(vars.getValue());
}
}
回答2:
here is a super simplified answer, if you want more details just add a comment ;)
class SomeVariables{
String s;
int dontneed;
}
class MainClass{
// this is ok
SomeVariables vars= new SomeVariables();
// not allowed here, must be on method, main for example
vars.s = "why this doesnt work?. IDE says Uknown class 'vars.s'";
// not allowed here, must be on method, main for example
System.out.println(vars.s); // Accesing it also doesnt work
void ChangeValue(){
// it works because is on scope and inside a method
vars.s = "why does this work?";
}
public static void main(String[]args){
// here sholud be your statements var.s = ... and System.out.println
}
}
来源:https://stackoverflow.com/questions/53675473/why-cant-i-modify-class-member-variable-outside-any-methods