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

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

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.
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 9 - Inheritance.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
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.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance Part III. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke.
Chapter 10  Inheritance 1 Chapter 10 Inheritance.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
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.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Inheritance Motivation –Code reuse –Conceptual modeling.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
ITM 352 Class inheritance, hierarchies Lecture #.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
What is inheritance? It is the ability to create a new class from an existing class.
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.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Chapter 10 Inheritance. Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism.
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.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
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.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
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 13 - Inheritance.
Data Structures and Algorithms revision
Inheritance In the real world, objects aren’t usually one-of-a-kind.
CSC 205 Java Programming II
Lecture Notes – Inheritance (Ch 9-10)
Inheritance in Java.
Chapter 9 – Inheritance.
Chapter 10 – Inheritance Big Java by Cay Horstmann
Extending Classes.
Polymorphism and access control
د.سناء الصايغ الفصل الأول البرمجة الشيئية
Adapted from Java Concepts Companion Slides
Presentation transcript:

Inheritance Part II

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

Implementing Remaining Methods public class CheckingAccount extends BankAccount {... public void withdraw(double amount) { transactionCount++; // Now subtract amount from balance super.withdraw(amount); }

Implementing Remaining Methods (Cont’d) public void deductFees() { private static final int FREE_TRANSACTIONS = 3; private static final double TRANSACTION_FEE = 2.0; if (transactionCount > FREE_TRANSACTIONS) { double fees = TRANSACTION_FEE * (transactionCount - FREE_TRANSACTIONS); super.withdraw(fees); } transactionCount = 0; }... }

Overriding vs. Overloading When you override a method, the new method definition in the derived class has the same name and the same number of types of parameters as the method definition in the base class. When the name is the same, but the number or types of the parameters differs, whether in the base class or in the derived class, the method is overloaded in the derived class.

Overriding vs. Overloading (Cont’d) Example: in the class SavingAccount and in class BankAccount overloads the method getName() since the two methods have different parameter lists.  It should be noted that both methods [ getName(String title) and String getName() ] are available in class SavingAccount ! public String getName(String title) public String getName()

A Subtle Point About Overloading and Overriding Even when two methods have the same number of parameters, a difference in parameter type is sufficient to qualify for overloading. But, a reference to an ancestor class type can refer to a descendant type. Hence an overridden method in an ancestor class sometimes needs to be invoked explicitly using super.

The final Modifier You can prevent a method definition from being overridden by adding the word final to the method heading. Example: This is used rarely, but it produces more efficient code. public final void someMethod() { … }

The final Modifier (Cont’d) An entire class can be declared final, in which case it cannot be used as a superclass to derive another class. Example: Therefore, the class Math can NOT be extended or used as a superclass. package java.lang; public final class Math { … }

Private Instance Variables in the Base Class Private instance variables inherited from a base class cannot be accessed directly. Instead, they must be accessed using a method that is not declared private. While this may seem inconvenient, it provides an important mechanism for controlling access and changes to instance variables in the base class.

Private Methods in the Base Class Like private instance variables, private method inherited from a base class cannot be accessed directly. Instead, they, too, must be accessed using a method that is not declared private. This, too, provides an important mechanism for controlling access to methods in the base class.

Common Error: Shadowing Instance Fields A subclass has no access to the private instance fields of the superclass Beginner's error: "solve" this problem by adding another instance field with same name: public class CheckingAccount extends BankAccount { private double balance; // Don't public void deposit(double amount) { transactionCount++; balance = balance + amount; }... }

Common Error: Shadowing Instance Fields (Cont’d) Now the deposit method compiles, but it doesn't update the correct balance! Figure 1: Shadowing Instance Fields

Subclass Construction super followed by a parenthesis indicates a call to the superclass constructor public class CheckingAccount extends BankAccount { public CheckingAccount(double initialBalance) { // Construct superclass super(initialBalance); // Initialize transaction count transactionCount = 0; }... }

Subclass Construction (Cont’d) Must be the first statement in subclass constructor If subclass constructor doesn't call superclass constructor, default superclass constructor is used  Default constructor: constructor with no parameters  If all constructors of the superclass require parameters, then the compiler reports an error

Syntax: Calling a Superclass Constructor ClassName(parameters){ super(parameters);... } Example: public CheckingAccount(double initialBalance) { super(initialBalance); transactionCount = 0; } Purpose: To invoke a constructor of the superclass. Note that this statement must be the first statement of the subclass constructor.

Converting Between Subclass and Superclass Types It is OK to convert subclass reference to superclass reference SavingsAccount collegeFund = new SavingsAccount(10); BankAccount anAccount = collegeFund; Object anObject = collegeFund;

Converting Between Subclass and Superclass Types (Cont’d) The three object references stored in collegeFund, anAccount, and anObject all refer to the same object of type SavingsAccount Figure 2: Variables of Different Types Refer to the Same Object

Converting Between Subclass and Superclass Types (Cont’d) Superclass references don't know the full story: When you convert between a subclass object to its superclass type:  The value of the reference stays the same–it is the memory location of the object  But, less information is known about the object anAccount.deposit(1000); // OK anAccount.addInterest(); // No--not a method of the class to which anAccount belongs

Converting Between Subclass and Superclass Types (Cont’d) Why would anyone want to know less about an object?  Reuse code that knows about the superclass but not the subclass: Can be used to transfer money from any type of BankAccount public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); }

Converting Between Subclass and Superclass Types (Cont’d) Occasionally you need to convert from a superclass reference to a subclass reference This cast is dangerous: if you are wrong, an exception is thrown BankAccount anAccount = (BankAccount) anObject;

Converting Between Subclass and Superclass Types (Cont’d) Solution: use the instanceof operator instanceof : tests whether an object belongs to a particular type if (anObject instanceof BankAccount) { BankAccount anAccount = (BankAccount) anObject;... }

Syntax: The InstanceOf Operator object instanceof TypeName Example: if (anObject instanceof BankAccount) { BankAccount anAccount = (BankAccount) anObject;... } Purpose: To return true if the object is an instance of TypeName (or one of its subtypes), and false otherwise

The class Object: The Cosmic Superclass All classes defined without an explicit extends clause automatically extend Object Figure 3: The Object Class is the Superclass of Every Java Class

The class Object: The Cosmic Superclass (Cont’d) Most useful methods:  String toString()  boolean equals(Object otherObject)  Object clone() Good idea to override these methods in your own classes

Overriding the tostring() Method Returns a string representation of the object Useful for debugging: Rectangle box = new Rectangle(5, 10, 20, 30); String s = box.toString(); // Sets s to "java.awt.Rectangle[x=5,y=10,width=20,height=30]"

Overriding the tostring() Method (Cont’d) The toString() method is called whenever you concatenate a string with an object: The Object.toString() method prints class name and the hash code of the object "box=" + box; // Result: "box=java.awt.Rectangle[x=5,y=10,width=20,height=30]" BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to something like

Overriding the tostring() Method (Cont’d) To provide a nicer representation of an object, override the toString() method: This works better: public String toString() { return "BankAccount[balance=" + balance + "]"; } BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to "BankAccount[balance=5000]"