1. Mark what new material is covered and what is not covered in Chapter 12:
2. Define a class Student in which each object has a name and a GPA. Do not forget to include a constructor, accessor methods, and mutator methods.
Solution:
public class Student{
private String name;
private double gpa;
public Student(String aname, double agpa){name = aname; gpa = agpa;}
public String getName(){return name;}
public double getGpa(){return gpa;}
public void setName(String newName){name = newName;}
public void setGpa(double newGpa){gra = newGpa;}
}
3. Considering Student as a superclass, define a subclass
CsStudent in which each object has an additional field: GPA
in CS classes.
Solution:
public class CsStudent extends Student{
private double gpaInCs;
public CsStudent(String aname, double agpa, double agpaInCs)
{super(aname, agpa); gpaInCs = agpaInCs;}
public double getGpaInCs(){return gpaInCs;}
public void setGpaInCs(double newGpaInCs){graInCs = newGpaInCs;}
}
4. In the main method, define a new object of type
CsStudent with your name and perfect GPAs, and return its
perfect GPA. Trace your code step-by-step.
Solution:
CsStudent i = new CsStudent("Luis Garcia", 4.0, 4.0);
double myGpa = i.getGpa();
Tracing:
on the first line, we call a constructor method:
-----------------
| ------------- |
| | Luis Garcia | |
| ------------ |
| aname |
| ------------ |
| | 4.0 | |
| ------------ |
| agpa |
| ------------ |
| | 4.0 | |
| ------------ |
| agpaInCs |
|-----------------|
| |
| |
| |
| |
| |
| |
| |
| |
-----------------
CsStudent
this method, in its turn, calls a constructor method of the superclass:
-----------------
| ------------- |
| | Luis Garcia | |
| ------------ |
| aname |
| ------------ |
| | 4.0 | |
| ------------ |
| agpa |
|-----------------|
| |
| |
| |
| |
| |
| |
| |
| |
-----------------
Student
after the first line, we get a new object
-----------------
| ------------- |
| | Luis Garcia | |
| ------------ |
| name |
| ------------ |
| | 4.0 | |
| ------------ |
| gpa |
| ------------ |
| | 4.0 | |
| ------------ |
| gpaInCs |
|-----------------|
| |
| |
| |
| |
| |
| |
| |
| |
-----------------
i
after the second line, we get
----------
| 4.0 |
----------
mygpa