43.3k views
3 votes
1)Create a class Student according to the following requirements:

a) A student has four attributes: id, name, GPA and major.
b) Add the default constructor (no parameters).
c) Add a constructor with four parameters to initialize all the attributes by specific values.
d) Add all the required setter methods.
e) Add all the required getter methods.
f) Add the method change Major.

2) Create a Driver class. that has the main method, in which:
a) Create a student object (obj1), provide all values for the class attributes.
b) Create another student object (obj2), provide all values for the class attributes.
c) Print the values of obj1 and obj2 fields.
d) Change the major for obj1.
e) Change the major for obj2.
f) Print the values of obj1 and obj2 fields.
java oop

User Spyryto
by
7.8k points

1 Answer

1 vote

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());
}
}
User Andrew Rollings
by
7.8k points