Monday, January 29, 2007

Lecture 11

Inheritance

  • 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
public class Student
{
//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')
Access Specifiers

  • 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
Package and Access Restrictions
  • 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
Creating and Using Package

  1. Create a package
    1. think of a name for package
      1. all lower case letters
    2. create a directory with that name
      1. move all files to that directory
    3. in all files in student write the following statement as the first line
      1. package student;
    4. using the package
      1. at the top you write the following
        1. import student.*;

No comments: