Modify the Course class to add a clone method to perform a deep copy on the stud
ID: 3814812 • Letter: M
Question
Modify the Course class to add a clone method to perform a deep copy on the students field. You can use a utility method for performing this deep copy.
public class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
students[numberOfStudents] = student;
numberOfStudents++;
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
/*******clone method goes here**********/
}
This needs to be done in Java
Explanation / Answer
import java.util.Arrays;
public class Course implements Cloneable {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
public Course(String courseName, String[] students, int numberOfStudents) {
super();
this.courseName = courseName;
this.students = students;
this.numberOfStudents = numberOfStudents;
}
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
students[numberOfStudents] = student;
numberOfStudents++;
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
/******* clone method goes here **********/
public Object clone() throws CloneNotSupportedException {
Course c = new Course(courseName, Arrays.copyOf(students, 1), numberOfStudents);
return c;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.