InheritanceInheritance
CSC 171 FALL 2004
LECTURE 18
READINGREADING
Read Horstmann, Chapter 11
Design MethodologyDesign Methodology
1. Problem Definition
2. Requirements Analysis
3. Architecture
4. Construction
5. Testing
6. Future Improvements
Classes and ObjectsClasses and ObjectsObject oriented programs
– Define classes of objects– Make specific object out of class definitions– Run by having the objects interact
A class is a type of thing– Instructor
An object is a specific thing– Ted
An object is an instance of a class
HierarchiesHierarchies
Humans have found that organizing concepts into hierarchies a useful method of organizing information
HIERARCHIESHIERARCHIESHierarchies are nested groupings.
Examples of hierarchies Levels of organization in our bodies:
– Organism: Organ Systems: Organs: Tissues: Cells: Organelles Ecology:
– Biome: Community: Population: Organism Political boundaries:
– USA: New York State: Monroe County: City of Rochester
Notice how each group is completely subordinate to any group on its left.
Inheritance HierarchiesInheritance HierarchiesObject oriented languages, such as JAVA
allows us to group classes into inheritance hierarchies.
The most general classes are near the root– superclasses
The more specific classes are near the leaves– Subclasses
Subclasses inherit attributes from superclasses
Example: Banking SystemsExample: Banking Systems
Consider a system that supports Savings and Checking accounts– What are the similarities?– What are the specifics
AccountsAccounts
Both savings and Checking accounts support the idea of– Balance– Deposit– Withdraw
Savings accounts pay interest checking accounts do not
Checking accounts have transaction fees, savings accounts do not
Super & Sub classesSuper & Sub classesMore general concepts are in super classesMore specific concepts are in sub classesSub classes extend (inherit from)
superclasses
Why inheritance?Why inheritance?
The power of inheritance is that sub-classes inherit the capabilities of the super-classes they extend
This reduces code redundancy
Example: Banking systemsExample: Banking systems
Bank accounts are a type of object Savings accounts are a type of bank account Checking Accounts are bank accounts
public class BankAccount { . . . }public class SavingsAccount extends BankAccount { . . .}public class CheckingAccount extends BankAccount { . . .}
BankAccountBankAccount
Instance variable “balance”Methods “deposit” and “withdraw”
public class BankAccount { public void deposit (double amount) { balance += amount; }
public void withdraw(double amount) { if (amount <= balance)
balance -= amount; }
private double balance; }
SavingsAccountSavingsAccount
A bank account with an interest rate
public class SavingsAccount extends BankAccount { public SavingsAccount(double rate) { interestRate = rate; }
public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); }
private double interestRate; }
Inheritance and MethodsInheritance and Methods
Override method: Supply a different implementation of a method that exists in the superclass
Inherit method: Don't supply a new implementation of a method that exists in the superclass
Add method: Supply a new method that doesn't exist in the superclass
Inheritance and FieldsInheritance and Fields
Inherit field: All fields from the superclass are automatically inherited
Add field: Supply a new field that doesn't exist in the superclass
Can't override fields
Checking AccountChecking Account
A Bank Account with transaction feesNeed to keep tack of transactions
Checking AccountChecking Account
public class CheckingAccount extends BankAccount { private int transactionCount;
public CheckingAccount() { transactionCount = 0; }
}
public void deposit(double amount) { transactionCount++; super.deposit(amount);}
public void withdraw(double amount) { transactionCount++; super.deposit(amount);}
ExcerciseExcercise
Define a base class “Employee”– Employees have names– Define constructor
public class Employee {private String name;
public Employee(String name) {this.name = name;
}public String name() { return name;}
}
ExcerciseExcercise
Define a sub class “HourlyEmployee”– Names, hourly rates, and hours worked– Define constructor, clockhours and “getPay()”
public class HourlyEmployee extends Employee {private double wage, hoursworked;
public HourlyEmployee(String name, double wage) { super(name);this.wage = wage;hoursworked = 0;
}
public void clockHours(double hours) {hoursworked += hours;
}public double getPay() {
double pay = hoursworked * wage;hoursworked = 0 ;return pay;
}}
ExcerciseExcercise
Define a sub-class “SalaryEmployee”– Names and annual Salary– Define constructor, and “getPay()” (montly)
public class SalaryEmployee extends Employee {private double annualSalary;
public SalaryEmployee(String name, double salary) { super(name);annualSalary = salary;
}
public double getPay() {return annualSalary / 12;
}}
TERMINOLOGYTERMINOLOGY
A base class is often called a parent class. A sub-class is then called a child class (or derived class)
Parents of parents are called ancestor classes
Children of children are called descendent classes
Overriding vs. OverloadingOverriding vs. Overloading
Overloading refers to having a different configuration of parameters for the same method name
Overriding refers to the redefinition of a method in a subclass
ACCESS ISSUESACCESS ISSUES
private instance variables or methods in a super (base,parent) class are not accessible in sub (derived, child) classes.
So, private methods and variable are effectively not inherited.– They are “there” but you have to use the super-
class accessor and mutator methods.
ProtectedProtected
protected methods and variables can be accessed inside derived classes, or in any class in the same package.
Package AccessPackage Access
If you don not place any of public, private, or protected before an instance variable or method definition, then it will have package access (also know as default access or friendly access). It will be visible to any class in the same package, but not outside.