Inheritance Part III. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke.

Slides:



Advertisements
Similar presentations
Chapter 13 - Inheritance. Goals To learn about inheritance To learn about inheritance To understand how to inherit and override superclass methods To.
Advertisements

IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Computer Science A 9: 3/11. Inheritance Today: Inheritance (JC – CCJ ) I have to leave at 11am (but you can stay)
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Part I. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
I NHERITANCE Chapter 10. I NHERITANCE Mechanism for enhancing existing classes You need to implement a new class You have an existing class that represents.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.
Inheritance. Class Relationships Composition: A class contains objects of other class(es) (actually, references to such objects) –A “has a” relationship.
Chapter 13 Inheritance. An Introduction to Inheritance Inheritance: extend classes by adding methods and fields (variables) Example: Savings account =
CHAPTER 11 INHERITANCE CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Ten: Inheritance.
Chapter 2 – An Introduction to Objects and Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
The Java Programming Language  Simple – but abstract  Safe  Platform-independent ("write once, run anywhere")  Has a Rich growing library  Designed.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Object Oriented Design CSC 171 FALL 2001 LECTURE 12.
Chapter 10  Inheritance 1 Chapter 10 Inheritance.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Chapter 3 Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To understand.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Inheritance Motivation –Code reuse –Conceptual modeling.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
ITM 352 Class inheritance, hierarchies Lecture #.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Inheritance.
Often categorize concepts into hierarchies: Inheritance Hierarchies Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance in Java. RHS – SOC 2 What is inheritance (in Java)? Inheritance is a mechanism for enhancing existing classes What does that mean…? Defining.
 Sometimes a new class is a special case of the concept represented by another ◦ A SavingsAccount is-a BankAccount ◦ An Employee is-a Person  Can extend.
Inheritance CSC 171 FALL 2004 LECTURE 18. READING Read Horstmann, Chapter 11.
Java Programming Week 4: Inheritance (Chapter 10).
Topic 4 Inheritance.
CHAPTER 11 INHERITANCE. CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
CSC 205 Java Programming II Inheritance Inheritance In the real world, objects aren’t usually one-of-a-kind. Both cars and trucks are examples of.
Chapter 10 Inheritance. Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Encapsulation ◦ Blackbox concept Data and method(s) Hidden details InterfaceEffect(s) methods called class.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
 Sometimes a new class is a special case of the concept represented by another ◦ A SavingsAccount is-a BankAccount ◦ An Employee is-a Person  Can extend.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance INHERITANCE: extend existing classes by adding or redefining methods, and adding instance fields Suppose we have a class Vehicle: public class.
Chapter 13 Inheritance. Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 3: An Introduction to Classes 1 Chapter 3 An Introduction to Classes.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 3 Implementing Classes
1 Principles of Computer Science II Prof. Nadeem Abdul Hamid CSC 121 – Spring 2006 Lecture Unit 4 - Inheritance.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Polymorphism and access control. RHS – SOC 2 What is polymorphism? In general: the ability of some concept to take on different forms In Java: the ability.
Chapter Ten: Inheritance
Chapter 13 - Inheritance.
Lecture 3 John Woodward.
Data Structures and Algorithms revision
Chapter 3 – Implementing Classes
Lecture Notes – Inheritance (Ch 9-10)
Inheritance in Java.
Implementing Classes Yonglei Tao.
Computing with C# and the .NET Framework
Chapter Goals To become familiar with the process of implementing classes To be able to implement and test simple methods To understand the purpose and.
CSC 205 Java Programming II
Chapter Three - Implementing Classes
Chapter 10 – Inheritance Big Java by Cay Horstmann
Polymorphism and access control
د.سناء الصايغ الفصل الأول البرمجة الشيئية
Adapted from Java Concepts Companion Slides
Presentation transcript:

Inheritance Part III

Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package access control To understand the common superclass Object and to override its toString() and equals() methods

Overriding the equals() Method The equals() method tests for equal contents Figure 4: Two References to Equal Objects

Overriding the equals() Method (Cont’d) == tests for equal location Figure 5: Two References to the Same Object

Overriding the equals() Method (Cont’d) Define the equals() method to test whether two objects have equal state When redefining the equals() method, you cannot change object signature; use a cast instead: public class Coin {... public boolean equals(Object otherObject) { Coin other = (Coin) otherObject; return name.equals(other.name) && value == other.value; }... }

Overriding the equals() Method (Cont’d) You should also override the hashCode() method so that equal objects have the same hash code

Overriding the clone() Method Copying an object reference gives two references to same object: BankAccount account2 = account;

Overriding the clone() Method (Cont’d) Figure 6: Cloning Objects Sometimes, need to make a copy of the object

Overriding the clone() Method (Cont’d) Define the clone() method to make new object Use of the clone() method: Must cast return value because return type is Object BankAccount clonedAccount = (BankAccount) account.clone();

The Object.clone Method Creates shallow copies Figure 7: The Object.clone Method Makes a Shallow Copy

The Object.clone Method (Cont’d) Does not systematically clone all subobjects Must be used with caution It is declared as protected ; prevents from accidentally calling x.clone() if the class to which x belongs hasn't redefined clone to be public You should override the clone() method with care

UML Inheritance Diagrams Typically, a UML class diagram shows only as much as is needed for the design task at hand.

UML Inheritance Diagrams (Cont’d) Figure 8: UML Inheritance Diagram

An arrowhead points from a derived class to its base class, indicating an is-a relationship.  For example, a Student is-a Person. Inherited instance variables and methods can be found by following the arrowheads. UML Inheritance Diagrams (Cont’d)

More details of the inheritance hierarchy UML Inheritance Diagrams (Cont’d) Figure 9: UML Inheritance Diagram of Person and Student Classes

Access Control Java has four levels of controlling access to fields, methods, and classes:  public access Can be accessed by methods of all classes  private access Can be accessed only by the methods of their own class  protected access

Java has four levels of controlling access to fields, methods, and classes:  package access The default, when no access modifier is given Can be accessed by all classes in the same package Good default for classes, but extremely unfortunate for fields Access Control (Cont’d)

Recommended Access Levels Instance and static fields: Always private. Exceptions:  public static final constants are useful and safe  Some objects, such as System.out, need to be accessible to all programs ( public )  Occasionally, classes in a package must collaborate very closely (give some fields package access); inner classes are usually better

Methods: public or private Classes and interfaces: public or package  Better alternative to package access: inner classes In general, inner classes should not be public (some exceptions exist, e.g., Ellipse2D.Double ) Beware of accidental package access (forgetting public or private ) Recommended Access Levels (Cont’d)

Access Modifiers

File AccountTester.java 01: /** 02: This program tests the BankAccount class and 03: its subclasses. 04: */ 05: public class AccountTester 06: { 07: public static void main(String[] args) 08: { 09: SavingsAccount momsSavings 10: = new SavingsAccount(0.5); 11: 12: CheckingAccount harrysChecking 13: = new CheckingAccount(100); 14: 15: momsSavings.deposit(10000); 16:

File AccountTester.java 17: momsSavings.transfer(2000, harrysChecking); 18: harrysChecking.withdraw(1500); 19: harrysChecking.withdraw(80); 20: 21: momsSavings.transfer(1000, harrysChecking); 22: harrysChecking.withdraw(400); 23: 24: // Simulate end of month 25: momsSavings.addInterest(); 26: harrysChecking.deductFees(); 27: 28: System.out.println("Mom's savings balance = $“ 29: + momsSavings.getBalance()); 30: 31: System.out.println("Harry's checking balance = $“ 32: + harrysChecking.getBalance()); 33: } 34: }

File BankAccount.java 01: /** 02: A bank account has a balance that can be changed by 03: deposits and withdrawals. 04: */ 05: public class BankAccount 06: { 07: /** 08: Constructs a bank account with a zero balance. 09: */ 10: public BankAccount() 11: { 12: balance = 0; 13: } 14: 15: /** 16: Constructs a bank account with a given balance. initialBalance the initial balance 18: */

File BankAccount.java 19: public BankAccount(double initialBalance) 20: { 21: balance = initialBalance; 22: } 23: 24: /** 25: Deposits money into the bank account. amount the amount to deposit 27: */ 28: public void deposit(double amount) 29: { 30: balance = balance + amount; 31: } 32: 33: /** 34: Withdraws money from the bank account. amount the amount to withdraw 36: */

File BankAccount.java 37: public void withdraw(double amount) 38: { 39: balance = balance - amount; 40: } 41: 42: /** 43: Gets the current balance of the bank account. the current balance 45: */ 46: public double getBalance() 47: { 48: return balance; 49: } 50: 51: /** 52: Transfers money from the bank account to another account amount the amount to transfer other the other account 55: */

File BankAccount.java 56: public void transfer(double amount, BankAccount other) 57: { 58: withdraw(amount); 59: other.deposit(amount); 60: } 61: 62: private double balance; 63: }

File CheckingAccount.java 01: /** 02: A checking account that charges transaction fees. 03: */ 04: public class CheckingAccount extends BankAccount 05: { 06: /** 07: Constructs a checking account with a given balance. initialBalance the initial balance 09: */ 10: public CheckingAccount(double initialBalance) 11: { 12: // Construct superclass 13: super(initialBalance); 14: 15: // Initialize transaction count 16: transactionCount = 0; 17: } 18:

File CheckingAccount.java 19: public void deposit(double amount) 20: { 21: transactionCount++; 22: // Now add amount to balance 23: super.deposit(amount); 24: } 25: 26: public void withdraw(double amount) 27: { 28: transactionCount++; 29: // Now subtract amount from balance 30: super.withdraw(amount); 31: } 32: 33: /** 34: Deducts the accumulated fees and resets the 35: transaction count. 36: */

File CheckingAccount.java 37: public void deductFees() 38: { 39: if (transactionCount > FREE_TRANSACTIONS) 40: { 41: double fees = TRANSACTION_FEE * 42: (transactionCount - FREE_TRANSACTIONS); 43: super.withdraw(fees); 44: } 45: transactionCount = 0; 46: } 47: 48: private int transactionCount; 49: 50: private static final int FREE_TRANSACTIONS = 3; 51: private static final double TRANSACTION_FEE = 2.0; 52: }

File SavingsAccount.java 01: /** 02: An account that earns interest at a fixed rate. 03: */ 04: public class SavingsAccount extends BankAccount 05: { 06: /** 07: Constructs a bank account with a given interest rate. rate the interest rate 09: */ 10: public SavingsAccount(double rate) 11: { 12: interestRate = rate; 13: } 14: 15: /** 16: Adds the earned interest to the account balance. 17: */

File SavingsAccount.java 18: public void addInterest() 19: { 20: double interest = getBalance() * interestRate / 100; 21: deposit(interest); 22: } 23: 24: private double interestRate; 25: }

File SavingsAccount.java Mom's savings balance = $ Harry's checking balance = $ Output: