{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}


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

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

View Full Document Right Arrow Icon
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
Background image of page 1

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

View Full Document Right Arrow Icon
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
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 6

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

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

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