csc2700lect02 - CSc 2700: Lecture # 2 Inheritance September...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CSc 2700: Lecture # 2 Inheritance September 2, 2008 1 Introduction Definition 1. Inheritance: the mechanism by which we define a class by extending the behavior of a preexisting class by adding methods and fields. For example, a savings account is a bank account with interest. class SavingsAccount extends BankAccount { new methods new instance fields } SavingsAccount automatically inherits all methods and instance fields of BankAccount. SavingsAccount collegeFund = new SavingsAccount(10); // Savings account with 10% interest collegeFund.deposit(500); // OK to use BankAccount method with SavingsAccount object In this case we called the extended class the superclass (BankAccount) and the extending class the subclass (Savings). Inheriting a class and imple- menting interface are two distinct concepts: subclass inherits the behavior and state of a superclass. One advantage of inheritance is it allows for code reuse. In Java, every class extends the Object class either directly or indi- rectly. In the subclass, we specify additional instance fields, methods, and change or override methods. 1 Program 1. public class SavingsAccount extends BankAccount { public SavingsAccount(double rate) { interestRate = rate; } public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } private double interestRate; } Encapsulation: addInterest calls getBalance rather than updating the bal- ance field of the superclass (field is private). Note that addInterest calls getBalance without specifying an implicit parameter (the calls apply to the...
View Full Document

This note was uploaded on 10/06/2009 for the course CSC 2700 taught by Professor Duncan during the Spring '08 term at LSU.

Page1 / 6

csc2700lect02 - CSc 2700: Lecture # 2 Inheritance September...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online