为什么我不能在任何方法之外修改类成员变量? [英] Why can't I modify class member variable outside any methods?

查看:98
本文介绍了为什么我不能在任何方法之外修改类成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些变量的类.当我在主类中实例化该类的对象时.我只能访问和修改一个方法(任何方法)中的成员变量;不在他们外面.这是为什么?我被困住了,似乎无法在Google上找到答案.

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

推荐答案

它不起作用,因为您是在无效的Java语法的构造函数或方法之外定义实例的.

It does not work because you are defining the instances outside of a constructor or methos which is not valid Java syntax.

可能的解决方法是:

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);
    }
}

但是您可能想要考虑保护您的类变量,例如将所有属性设置为SomeVariables,并使用settersgetters方法来获取和修改类本身中的值.例如:

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());
    }
}

这篇关于为什么我不能在任何方法之外修改类成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆