Given the following declaration:
class Student {
private double GPA;
private String name;
Student s = new Student();
public void setGPA(double GPA) {
this.GPA = GPA;
}enter code here
public double getGPA() {
return GPA;
}
}
Question: Assuming that s is an instance (object) of the class Student, what is the statement to assign 3.5 to the GPA for s?
Here is a solution, Your student class can be used to create object and we need some reference to that object in order to change the values. Here s
which is called instance of the student, that s
refers to your student. When you write new
word in java, it means you are creating some new object(in this case a student).
public class test {
public static void main(String [] args) {
Student s = new Student();
s.setGPA(3.5); //set Gpa
System.out.println(s.getGPA());
}
}
class Student {
private double GPA;
private String name;
public void setGPA(double GPA) {
this.GPA = GPA;
}
public double getGPA() {
return GPA;
}
}
Or you can use constructor in student class to initialize Gpa
when creating an object like this. However you can use setter and getter later to manipulate the values.
public class test {
public static void main(String [] args) {
Student s = new Student(5,"Khan");
System.out.println("The given Gpa is " + s.getGPA() + " and name is " + s.getName());
s.setGPA(3.5); //change Gpa
System.out.println(s.getGPA()+ "The gpa has been changed");
}
}
class Student {
private double GPA;
private String name;
public Student(double Gp,String Name) {
this.GPA = Gp;
this.name = Name;
}
public String getName() {
return this.name;
}
public void setGPA(double GPA) {
this.GPA = GPA;
}
public double getGPA() {
return GPA;
}
}