java,获取设置方法

标签 java methods get set

这个问题以前有人问过,但看了之后还是:

Java "Get" and "Set" Methods

Java Get/Set method returns null

还有更多我仍然不明白如何解决我的问题。

当使用另一个类的 get 方法访问一个类中的变量时,我收到值 null。

如何接收正确的值而不是空值?


这是我尝试从中获取变量的类(不包括所有内容)。

public class RLS_character_panel extends javax.swing.JPanel implements ActionListener, ItemListener { 

    private String name1 = "hello"; 

    public String getName1() { 
        return name1; 
    } 

    public void setName1(String name1) { 
        this.name1 = name1; 
    } 

} 

这是我尝试获取值的类(class)。此类扩展了 JFrame,以便我可以添加一个显示变量的 JPanel。 ( JPanel 是另一个类,称为: RLS_strid_panel ,添加到此框架上)。

public class RLS_strid_java extends JFrame { 

    RLS_character_panel test = new RLS_character_panel(); 

    String name1 = test.getName1(); 

    RLS_strid_panel p = new RLS_strid_panel(namn1); 

    // constructor
    public RLS_strid_java(String titel) { 
        super(titel); 
        this.setSize(1000, 772); 
        this.setVisible(true); 
        this.setResizable(false); 
        this.add(p); 
    } 
}

Jpanel 显示为空。

最佳答案

要理解get和set,都与变量在不同类之间的传递方式有关。

get 方法用于从类中获取或检索特定的变量值。

设置值用于存储变量。

get 和 set 的全部意义在于相应地检索和存储数据值。

我在这个旧项目中所做的是我有一个 User 类,其中包含我在 Server 类中使用的 get 和 set 方法。

User类的get set方法:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

然后这是在我的服务器类的 run() 方法中实现的,如下所示:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

关于java,获取设置方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36102768/

相关文章:

Java 泛型 : convert List<TypeA> to List<TypeB>

Java/XML问题

C++ 将方法指针作为模板参数传递

java - 调用 equals() 的行中的 NPE

ios - AFNetworking POST 作为 GET 发送

java - If语句执行所有条件

java - 一旦返回某些内容,程序是否会停止执行?

java - sendkeys(keys.Down) 和 sendkeys(keys.Arrow_Down) 之间的区别

git - 如何在私有(private) GitLab 存储库中使用 Go

jsp - sendRedirect()可以用作post方法而不是get方法吗? -jsp/servlet