Java 这段代码运行需要getter和setter吗?
我在下面(5节课)中包含了我的所有代码,用于一个简单的学生数据库 我与一些人共同编写了这段代码,他们认为在名称、地址和学生类中必须包含当前存在的所有getter和setter。我认为没有它们,代码将正常工作,它们不是必需的,应该删除吗?如果它们是必要的,有人能解释为什么或者有人能确认它们不是必要的吗 地址类 名称类 学生班 大学社区班Java 这段代码运行需要getter和setter吗?,java,setter,getter,Java,Setter,Getter,我在下面(5节课)中包含了我的所有代码,用于一个简单的学生数据库 我与一些人共同编写了这段代码,他们认为在名称、地址和学生类中必须包含当前存在的所有getter和setter。我认为没有它们,代码将正常工作,它们不是必需的,应该删除吗?如果它们是必要的,有人能解释为什么或者有人能确认它们不是必要的吗 地址类 名称类 学生班 大学社区班 您始终可以将属性设置为public或protected或使用默认范围并访问它们(前提是类位于适当的包中) 也就是说,使用二传手和传接手总是一个好的实践。它简化了对
您始终可以将属性设置为
public
或protected
或使用默认范围并访问它们(前提是类位于适当的包中)
也就是说,使用二传手和传接手总是一个好的实践。它简化了对正在设置的值的控制。例如。你可以把支票放在你的集合中,这样年龄就不会少于4岁
public void setAge(int age) throws Exception {
if (age <= 3) {
throw new Exception("Age must be more than 3");
}
this.age = age;
}
public void setAge(int age)引发异常{
和
if(age我不明白为什么此时需要它们,尽管删除它们很容易验证。由于Java是一种编译语言,如果代码的其他部分使用了这些方法,通常在编译时就会出现错误(除非您使用的部分代码或框架使用了反射) 也许与您一起编写代码的人正计划添加某种需要这些方法的对象关系映射框架
就我个人而言,我想说的是,你永远不应该添加未使用的代码。代码库复杂性的主要因素是代码行数,因此没有理由在代码库中添加任何未使用的代码。为了支持SJuan76的编写,与另一个编写相反,这需要说明: 通过从一开始就建立和使用getter/setter,您已经使您的代码能够在将来进行所有边界检查、日志记录等(如果您现在不这样做),而不需要客户机代码适应到getter/setter的转换 这是一个最佳实践,可以为您节省更多的时间
<>你应该始终认为你今天编写的代码将为明天的代码建立接口。第一次得到它的正确性/灵活性/可维护性。注意,对于GETER和SETTER的java约定是<代码> GETFOStfoo< <代码>,而不是<代码> Foo
和Stfoo
(我相信Qt就是这么做的。)谢谢你这么快的回复。我会随着年龄的变化而改变。这是我的一个错误。用出生日期来代替是完全有道理的!我想你没有抓住问题的关键,假设没有一个接受者和接受者等同于公开的(无论如何不是私人的)文件。我认为真正的问题是-你真的需要设置器和获取器才能使具有私有字段的类完全有效吗?很抱歉在回复中评论了两次。我不知道如何编辑我的第一个回复。但我最初的问题是,根据代码,我是否要从名称、地址和学生中删除设置器和获取器类的代码会起作用吗?我理解它们的价值以及为什么应该使用它们,但据我所知,它们在当前代码中没有被使用,它们就在那里,可以被删除。这是一个准确的假设吗?不。意味着属性只能由类的方法访问。如果存在,则不相关是setter或getter或任何其他使用它的方法。若要访问其他类的属性,只需将作用域更改为private
、public
或默认作用域。是否存在getter/setter或其他方法并不相关。当然,如果使用getter/setter,则最好使属性protected
这样您就可以确保对它们的访问不是通过适当的方法进行的。我注释掉了Name类中的getter和setter,并且代码编译时没有错误,因此它们目前是冗余的。我认为最好的方法是编辑代码,使它们不再是冗余的,但我有点迷路了如果我诚实的话,那么最好的方法是什么呢?如果我以年龄为例,因为你也做了同样的事情。我该如何进行更改,以便只能通过getter和setter访问它?我知道我必须让Student()首先,在学生课堂上使用私有。如果你说在公共/受保护的属性上使用getter/setter,那么我会同意。如果你说在每个私有字段中盲目添加getter(尤其是setter),我会强烈反对。有些属性可能不打算更改(出生日期是一个很好的例子,数据库ID是一个更好的例子)尤其是因为你今天编写的代码明天可能会建立一个接口,至少应该考虑一下。@ivarni我同意。关键是现在要以最有用/最灵活的方式定义正确的接口。以后添加元素是一种破坏性最小的更改。将getter/setter添加到因此,私有元素的破坏性较小。将访问权限从字段更改为getter/setter是破坏性的。[所有更改都会破坏序列化]我注释掉了Name类中的所有getter和setter,程序没有错误,因此我解决了这个问题。我认为现在的方法是编辑代码,以便实际使用getter和setter。是的,关于它为什么被否决的注释会很好,因为我不确定人们不同意哪一部分。private
public class Name{ private String firstName, lastName; public Name (String firstName, String lastName){ this.firstName = firstName; this.lastName = lastName; } public void setFirstName(String firstName){ this.firstName = firstName; } public void setLastName(String lastName){ this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } /** Returns first name concatenated to last name */ public String toString() { return firstName + " " + lastName; } }
public class Student { private Name name; // This is calling from the Name class, giving it the name 'name' private Address address; // This calls from Address, giving it the name 'address' private char gender; private String course, college; private int gradePointAverage, id, age, level; public Student(int id, String firstName, String lastName, String street, String area, String city, String country, int age, char gender, String college, String course, int level, int gradePointAverage){ //This is the list of variables called from the Student class this.id = id; this.name = new Name(firstName, lastName); this.address = new Address(street, area, city, country); this.age = age; this.gender = gender; this.college = college; this.course = course; this.level = level; this.gradePointAverage = gradePointAverage; } public int getId(){ return id; } public String getName(){ return name.toString(); } public String getAddress(){ return address.toString(); } public int getAge(){ return age; } public char getGender(){ return gender; } public String getCollege(){ return college; } public int getLevel() { return level; } public String getCourse() { return course; } public int getGradePointAverage() { return gradePointAverage; } public void printStudent() { System.out.println("The Student " + name.toString() + " is logged under the student ID number " + id + "."); System.out.println("They live at " + address.toString() + " and their age is " + age + "."); System.out.println("Their gender is " + gender + "."); System.out.println("The student studies at " + college + " attending classes in " + course + "."); System.out.println("Their level is " + level + " and the student grade average in points is " + gradePointAverage + "."); System.out.println(); } }
import java.util.*; public class CollegeCommunity { private ArrayList<Student> students; // Setting up an arraylist to store student details public CollegeCommunity() { students = new ArrayList<Student>(); } public void addStudent(Student student) // adds a student. { students.add(student); // .add method command. } public void removeStudent(int id) // deleting a student, after being passed id to locate desired student. { for (int i=0; i<students.size(); i++ ){ // using a loop to decide what student to remove by matching the student ID which was passed to the method with the student ID's on record. Once there's a match, the student will be removed (.remove). if(students.get(i).getId()==id) { students.remove(i); } } } public void showStudent(int id) // same as remove above but instead using print command to view details of particular student. { for (int i=0; i<students.size(); i++ ){ if(students.get(i).getId()==id) { students.get(i).printStudent(); } } } public void showAllStudents() { for (int i=0; i<students.size(); i++ ){ // This loop command will display ALL student details as no specific ID was passed, so it will run as long as value 'i' is less than student.size. int id=students.get(i).getId(); showStudent(id); } } public void showStudentsInCourse(String course) // This will show students in a particular course. { for(int i=0; i<students.size(); i++ ){ // Loop is same as remove but comparing the string course with the course of each student. .equals is used to compare strings. if(students.get(i).getCourse().equals(course)){ int id=students.get(i).getId(); showStudent(id); } } } public int calculateGradePointAverage() // calculating the grade point average as a percentage { int total = 0; for (int i = 0; i < students.size(); i++ ){ total = total + students.get(i).getGradePointAverage(); // total is calculated as it loops, each students score (getGradePointAverage). } total = total / students.size(); // final figure is total divided by the number of students, to give an average score. return total; } }
import java.util.*; public class TestSystem { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Student student; CollegeCommunity collegeCommunity = new CollegeCommunity(); // New CollegeCommunity created called 'collegeCommunity'. int id, age, level, gradePointAverage; // ints created for student id, age, level of course, and the grade point value String fName,lName, street, area, city, country, course, college; // first name, last name strings created char gender; // character gender created boolean finish = false; // boolean finish has value of False. do { switch(getMenu()) { case '1': System.out.println(); System.out.print("Please enter a new Student ID > "); id = sc.nextInt(); sc.nextLine(); System.out.println(); System.out.print("Please enter the Student's first name > "); fName = sc.nextLine(); System.out.println(); System.out.print("Please enter the Student's last name > "); lName = sc.nextLine(); System.out.println(); System.out.print("Please enter the street > "); street = sc.nextLine(); System.out.println(); System.out.print("Please enter the area > "); area = sc.nextLine(); System.out.println(); System.out.print("Please enter the city > "); city = sc.nextLine(); System.out.println(); System.out.print("Please enter the country > "); country = sc.nextLine(); System.out.println(); System.out.print("Please enter the age > "); age = sc.nextInt(); sc.nextLine(); System.out.println(); System.out.print("Please enter the gender > "); gender = sc.nextLine().charAt(0); System.out.println(); System.out.print("Please enter the college > "); college = sc.nextLine(); System.out.println(); System.out.print("Please enter the course > "); course = sc.nextLine(); System.out.println(); System.out.print("Please enter level > "); level = sc.nextInt(); sc.nextLine(); System.out.println(); System.out.print("Please enter the average grade in points [0-100] > "); gradePointAverage = sc.nextInt(); sc.nextLine(); System.out.println(); student = new Student(id, fName, lName, street, area, city, country, age, gender, college, course, level, gradePointAverage); collegeCommunity.addStudent(student); break; case '2': System.out.println(); System.out.print("Please enter the student ID number > "); id = sc.nextInt(); sc.nextLine(); // this will delete the student selected collegeCommunity.removeStudent(id); System.out.println(); System.out.print("Student " + id + " has been deleted."); System.out.println(); System.out.println(); break; case '3': System.out.println(); System.out.print("Please enter the student ID number > "); id = sc.nextInt(); sc.nextLine(); // This will allow for the details of the selected student to be displayed. Calls stored data from community college. collegeCommunity.showStudent(id); System.out.println(); System.out.println(); break; case '4': System.out.println(); // This will show all of the students stored in the system. collegeCommunity.showAllStudents(); System.out.println(); break; case '5': System.out.println(); System.out.print("Please enter the course > "); course = sc.nextLine(); // This will show students that are enrolled in a chosen course. collegeCommunity.showStudentsInCourse(course); System.out.println(); break; case '6': System.out.println(); System.out.print("The Average grade score is " + collegeCommunity.calculateGradePointAverage() + "%"); System.out.println(); break; case 'x': case 'X': finish = true; // boolean value changes to true if X is selected System.exit(0); break; default: System.out.println(); System.out.println("That is an invalid selection."); System.out.println(" Please try again"); break; } }while (!finish); } public static char getMenu() { Scanner sc = new Scanner(System.in); System.out.println(); System.out.println("This is your community college menu"); System.out.println("Please select from the menu options below"); System.out.println(); System.out.println("1 Add a Student"); System.out.println(); System.out.println("2 Delete a Student"); System.out.println(); System.out.println("3 Show details on an individual student"); System.out.println(); System.out.println("4 Show details on all students"); System.out.println(); System.out.println("5 Shows details on all students on a course"); System.out.println(); System.out.println("6 Display the average grade (points)"); System.out.println(); System.out.println("X Exit"); System.out.println(); System.out.println(); System.out.print("Please make selection > "); return sc.next().charAt(0); } }
myStudent.age = 9;
public void setAge(int age) throws Exception { if (age <= 3) { throw new Exception("Age must be more than 3"); } this.age = age; }