Java Reference
In-Depth Information
figure 4.2
The Student class
stores name, age,
address, phone
number, and gpa via
copy-and-paste.
1 class Student
2 {
3 public Student( String n, int ag, String ad, String p,
4 double g )
5 { name = n; age = ag; address = ad; phone = p; gpa = g; }
6
7 public String toString( )
8 { return getName( ) + " " + getAge( ) + " "
9 + getPhoneNumber( ) + " " + getGPA( ); }
10
11 public String getName( )
12 { return name; }
13
14 public int getAge( )
15 { return age; }
16
17 public String getAddress( )
18 { return address; }
19
20 public String getPhoneNumber( )
21 { return phone; }
22
23 public void setAddress( String newAddress )
24 { address = newAddress; }
25
26 public void setPhoneNumber( String newPhone )
27 { phone = newPhone; }
28
29 public double getGPA( )
30 { return gpa; }
31
32 private String name;
33 private int age;
34 private String address;
35 private String phone;
36 private double gpa
37 }
each other, in spite of their similarities. So, for instance, if we have a routine that
accepted a Person as a parameter, we could not send in a Student . We would thus
have to copy and paste all of those routines to make them work for these new
types.
Inheritance solves all three of these problems. Using inheritance, we would
say that a Student IS-A Person . We would then specify the changes that a Student
has relative to Person . There are only three types of changes that are allowed:
 
Search WWH ::




Custom Search