- say we are implementing a database of students in a course
- course is open to both undergraduate and graduate students
- obviously, the student records will be largely the same
- All students have
- Name
- Student Number
- Raw Percentage Score
- calculation of the letter grade is different between these students
- Undergrad
- A 80-100%
- B 70-80%
- C 60-70%
- D 50-60%
- F <50%
- Graduate Student
- A 80-100%
- B 70-80%
- F <70%
- inefficient to implement two separate classes when they overlap so much
- intuitively, both an undergrad and grad are types of students with certain features in common. it would be nice if student class could handle common functions and that this class could be extended
- Java allows us to extend this way using inheritance
- use the 'extends' keyword to declare child classes
{
//parent class
//takes care of common features
//student name / number / raw score
}
____________________________________
public class underGradStudent extends Student
{
//undergrad letter grade calculation
}
____________________________________
public class gradStudent extends Student
{
//grad letter grade calculation
}
_____________________________________
Inheritance and Constructors
- if you provide no constructor in a child class that will lead the compiler to call the default constructor of the parent and will generate an error if that doesn't exist.
- provide a constructor
- presumably you went to call the constructor of the parent class
- use the keyword 'super' (works like keyword 'this')
- private members are hidden from children
- this is sometimes valuable to have internal hidden variables that can't be manipulated outside your class
- protected objects are visible to children but not the public
- four valid access specifiers
- private
- most restricted
- class file only
- nothing
- access within package
- protected
- access within package and children
- public
- accessible everywhere
- ignore packages
- and java puts all files in the same package
- package
- package level access throughout the code
- Create a package
- think of a name for package
- all lower case letters
- create a directory with that name
- move all files to that directory
- in all files in student write the following statement as the first line
- package student;
- using the package
- at the top you write the following
- import student.*;
No comments:
Post a Comment