gpt4 book ai didi

java - 对象变量 vs setter 和 getter

转载 作者:行者123 更新时间:2023-11-29 09:43:01 25 4
gpt4 key购买 nike

<分区>

请教各位:下面是Student类,很简单然后下面 主要方法。首先是示例,其次是我。

public class Student{

private String name;
private int age;

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}

public int getAge(){
return age;
}

public void setAge(int age){
this.age = age;
}


}

这是主要方法。我不明白为什么要让它变得更复杂。通过将它与我的示例一起使用,我得到了相同的结果。

例子一

public class Main
{
public static void main(String[] args) {

Student johnReferenceVariable = getStudent("John",25);
System.out.println("Name : = "+johnReferenceVariable.getName());
System.out.println("Age : = "+johnReferenceVariable.getAge());


}


public static Student getStudent(String name, int age){
Student student = new Student();
student.setName(name);
student.setAge(age);
return student;
}
}

我的主类和方法示例:

public class Main
{
public static void main(String[] args) {

//Student johnReferenceVariable = getStudent("John",25);
Student student = new Student();
student.setName("Martin");
student.setAge(25);
System.out.println("Name : = "+student.getName());
System.out.println("Age : = "+student.getAge());

//System.out.println("Name : = "+johnReferenceVariable.getName());
//System.out.println("Age : = "+johnReferenceVariable.getAge());


}


//public static Student getStudent(String name, int age){
//Student student = new Student();
// student.setName(name);
//student.setAge(age);
//return student;
//}
}

非常感谢

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com