15. (10 marks) Write the student class that includes the followings. .Three inst
ID: 3709152 • Letter: 1
Question
15. (10 marks) Write the student class that includes the followings. .Three instance variables for age, gpa, and name. (They should not be directly accessed through a Student object.) .Constructor that accepts age, gpa, and name, and initializes the above three instance variables. .A method getGpa that returns the gpa. .A method setAge that accepts age and sets the instance variable age. A method getName that returns the name. A method tostring that returns a string of the description of the Student object. turns a string of the description of the student object.Explanation / Answer
/**Student class that has parameter constructor
* to set age,gpa and name and also has methods
* to set gpa and override toString method
* to display the Student object.*/
//Student.java
public class Student {
//instance variabels of class
private int age;
private double gpa;
private String name;
//parameterized constructor
public Student(int age, double gpa,
String name) {
this.age=age;
this.gpa=gpa;
this.name=name;
}
//Returns gpa
public double getGpa()
{
return gpa;
}
//Set gpa
public void setGpa(double gpa)
{
this.gpa=gpa;
}
//Returns name
public String getNasme()
{
return name;
}
/**Description of Student object*/
public String toString() {
return String.format("Name : %s, age : %d, gpa : %3.2f", name,age,gpa);
}
}
-----------------------------------------------------------------------
//Demonstrate Student
//StudentDriver.java
public class StudentDriver {
public static void main(String[] args) {
//Create an instance of Student with age, gpa and name
Student std=new Student(25, 4.5, "Johnson");
System.out.println("Student object ");
System.out.println(std.toString());
System.out.println("Modify gpa= 5.0");
std.setGpa(5);
System.out.println(std.toString());
}
}
-----------------------------------------------------------------------
Sample output:
Student object
Name : Johnson, age : 25, gpa : 4.50
Modify gpa= 5.0
Name : Johnson, age : 25, gpa : 5.00
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.