Final answer:
To create a Student class in Java, define the attributes id, name, GPA, and major, add a default constructor, a parameterized constructor, setters and getters for all attributes, and a method to change the major. A Driver class with a main method is used to create Student objects, print their details, change their majors, and print the updated details.
Step-by-step explanation:
Creating a Student Class in Java
To create a class Student with attributes id, name, GPA, and major, you would start by defining these attributes within the class. Then, you can add the required constructors and methods as described:
Here's an example of how the Student class might look:
public class Student {
private int id;
private String name;
private double GPA;
private String major;
// Default constructor
public Student() {
}
// Constructor with parameters
public Student(int id, String name, double GPA, String major) {
this.id = id;
this.name = name;
this.GPA = GPA;
this.major = major;
}
// Setter and Getter methods
public void setId(int id) { this.id = id; }
public int getId() { return id; }
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public void setGPA(double GPA) { this.GPA = GPA; }
public double getGPA() { return GPA; }
public void setMajor(String major) { this.major = major; }
public String getMajor() { return major; }
// Method to change major
public void changeMajor(String newMajor) {
this.major = newMajor;
}
}
Next, you would create a Driver class to test the Student class functionality:
public class Driver {
public static void main(String[] args) {
Student obj1 = new Student(1, "John Doe", 3.5, "Computer Science");
Student obj2 = new Student(2, "Jane Smith", 3.7, "Biology");
System.out.println(obj1.getName() + ", " + obj1.getMajor());
System.out.println(obj2.getName() + ", " + obj2.getMajor());
obj1.changeMajor("Information Technology");
obj2.changeMajor("Chemistry");
System.out.println(obj1.getName() + ", " + obj1.getMajor());
System.out.println(obj2.getName() + ", " + obj2.getMajor());
}
}