1 Principles of Computer Science II Prof. Nadeem Abdul Hamid CSC 121 – Spring 2006 Lecture Unit 4 - Inheritance.

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.
Inheritance Inheritance Reserved word protected Reserved word super
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.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
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.
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Inheritance Part III. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Chapter 10  Inheritance 1 Chapter 10 Inheritance.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
CS 106 Introduction to Computer Science I 04 / 21 / 2010 Instructor: Michael Eckmann.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
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.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
Predefined Classes in Java Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
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.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 10 Inheritance. Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
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.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
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 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
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)
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
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.
Lecture 12 Inheritance.
Inheritance and Polymorphism
Lecture Notes – Inheritance (Ch 9-10)
Chapter 10 – Inheritance Big Java by Cay Horstmann
Extending Classes.
Polymorphism and access control
Adapted from Java Concepts Companion Slides
Advanced Inheritance Concepts
Chapter 8 Class Inheritance and Interfaces
Presentation transcript:

1 Principles of Computer Science II Prof. Nadeem Abdul Hamid CSC 121 – Spring 2006 Lecture Unit 4 - Inheritance

2 Inheritance Extending classes by adding methods and fields Extended class = “Superclass” Extending class = “Subclass” Inheriting from a class is not the same as implementing an interface Subclass inherits behavior and state Advantage of inheritance: Code reuse CSC121 — Berry College — Spring 2006

3 Inheritance Diagram Every class in Java extends the Object class either directly or indirectly

4 Inheritance Hierarchies Sets of classes can form complex inheritance hierarchies

5 Swing Example

6 Subclass Methods Inherit method: Don’t supply a new implementation of a method that exists in superclass Superclass method can be applied to the subclass objects Override method: Supply a different implementation of a method that exists in the superclass Must have same signature (same name and same parameter types) If method is applied to an object of the subclass type, the overriding method is executed Add method: Supply a new method that doesn’t exist in the superclass New method can be applied only to subclass objects

7 Instance Fields Can’t override fields Can: Inherit a field: All fields from the superclass are automatically inherited Add a field: Supply a new field that doesn’t exist in the superclass What if you define a new field with the same name as a superclass field? Each object would have two instance fields of the same name Fields can hold different values Legal but extremely undesirable

8 Instance Fields // COMPILE ERROR ****** class A { private int x; //... } class B extends A { //... public void methodB() { x = 2; }

9 Common Error: Shadowing Fields public class CheckingAccount extends BankAccount { public void deposit(double amount) { transactionCount++; balance = balance + amount; }... private double balance; // Don't }

10 Invoking Superclass Methods class A { public void method() { System.out.println( "Method A" ); } class B { public void method() { method(); // infinite call to itself System.out.println( "Method B" ); } class A { public void method() { System.out.println( "Method A" ); } class B { public void method() { super.method(); System.out.println( "Method B" ); }

11 Subclass Constructors super followed by a parenthesis indicates a call to the superclass constructor 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

12 Converting Types Ok to convert subclass reference to superclass reference SavingsAccount collegeFund = new SavingsAccount(10); BankAccount anAccount = collegeFund; Object anObject = collegeFund;

13 Converting Between Types 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 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 anAccount.deposit(1000); // OK anAccount.addInterest(); // No--not a method of the class to which anAccount belongs public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); }

14 Casting Object Types 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 Solution: use the instanceof operator instanceof : tests whether an object belongs to a particular type BankAccount anAccount = (BankAccount) anObject; if (anObject instanceof BankAccount) { BankAccount anAccount = (BankAccount) anObject;...

15 Polymorphism In Java, type of a variable doesn't completely determine type of object to which it refers Method calls are determined by type of actual object, not type of object reference Compiler needs to check that only legal methods are invoked BankAccount aBankAccount = new SavingsAccount(1000); // aBankAccount holds a reference to a SavingsAccount BankAccount anAccount = new CheckingAccount(); anAccount.deposit(1000); // Calls "deposit" from CheckingAccount Object anObject = new BankAccount(); anObject.deposit(1000); // Wrong!

16 Polymorphism Polymorphism: ability to refer to objects of multiple types with varying behavior Polymorphism at work: Depending on types of amount and other, different versions of withdraw and deposit are called public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); }

17 Access Control Java has four levels of controlling access to fields, methods, and classes: public - Can be accessed by methods of all classes private - Can be accessed only by the methods of their own class package access (default) - Can be accessed by all classes in the same package (folder) protected - Can be accessed by all subclasses and by all classes in the same package

18 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)

19 Object: The Cosmic Superclass All classes defined without an explicit extends clause automatically extend Object

20 Object Class Methods Most useful methods: String toString() boolean equals(Object otherObject) Object clone() Good idea to override these methods in your classes

21 The toString() method Returns a string representation of the object Useful for debugging: toString is called whenever you concatenate a string with an object: Object.toString prints class name and the hash code of the object 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]" "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

22 Overriding the toString() method To provide a nicer representation of an object, override toString: 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]"

23 The equals() method Tests for equal contents: Figure 9: Two References to Equal Objects

24 The equals() method == tests for equal location Figure 10: Two References to the Same Object

25 Overriding equals() Define the equals method to test whether two objects have equal state When redefining equals method, you cannot change object signature; use a cast instead: (You should also override the hashCode method so that equal objects have the same hash code) public class Coin {... public boolean equals(Object otherObject) { Coin other = (Coin) otherObject; return name.equals(other.name) && value == other.value; }... }

26 The clone() method Copying an object reference gives two references to same object Sometimes, you need to make a copy of the object BankAccount account2 = account;

27 The clone() method Define clone method to make new object (see Advanced Topic 13.6) Use clone: Must cast return value because return type is Object BankAccount clonedAccount = (BankAccount) account.clone();

28 The Object.clone() method Creates shallow copies

29 Object.clone()… 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 (see Advanced Topic 13.6)

30 Scripting Languages Integrated with software for purpose of automating repetitive tasks Script: Very high-level, often short, program, written in a high-level scripting language Scripting languages: Unix shells, Tcl, Perl, Python, Ruby, Scheme, Rexx, JavaScript, VisualBasic,...

31 Characteristics of a script Glue other programs together Extensive text processing File and directory manipulation Often special-purpose code Many small interacting scripts may yield a big system Perhaps a special-purpose GUI on top Portable across Unix, Windows, Mac Interpreted program (no compilation+linking)

32 Why Scripts? Features of Perl and Python compared with Java, C/C++ and Fortran: shorter, more high-level programs much faster software development more convenient programming you feel more productive Reasons: no variable declarations, but lots of consistency checks at run time lots of standardized libraries and tools

33 Python - Prime Numbers result = [1] candidates = range(3,1000) base = 2 product = base while candidates: while product < 1000: if product in candidates: candidates.remove(product) product = product+base result.append(base) base = candidates[0] product = base del candidates[0] result.append(base) print result

34 Python - Address Book # create an empty address book dictionary addressBook = {} # read entries till an empty string print name = raw_input("Type the Name - leave blank to finish") while name != "": entry = raw_input("Type the Street, Town, Phone. Leave blank to finish") addressBook[name] = entry name = raw_input("Type the Name - leave blank to finish") # now ask for one to display name = raw_input("Which name to display?(blank to finish)") while name != "": print name, addressBook[name] name = raw_input("Which name to display?(blank to finish)")