Topic 4 Inheritance.

Slides:



Advertisements
Similar presentations
More on Classes Inheritance and Polymorphism
Advertisements

Chapter 13 - Inheritance. Goals To learn about inheritance To learn about inheritance To understand how to inherit and override superclass methods To.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
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.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
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.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
CS 106 Introduction to Computer Science I 11 / 19 / 2007 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.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
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.
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.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
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.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
Inheritance CSC 171 FALL 2004 LECTURE 18. READING Read Horstmann, Chapter 11.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
CHAPTER 11 INHERITANCE. CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
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…..
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,
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
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:
 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 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.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
1 More About Derived Classes and Inheritance Chapter 9.
Chapter 13 - Inheritance.
Modern Programming Tools And Techniques-I
Inheritance In the real world, objects aren’t usually one-of-a-kind.
Lecture 12 Inheritance.
Lecture Notes – Inheritance (Ch 9-10)
Inheritance in Java.
CSC 205 Java Programming II
Polymorphism and access control
Presentation transcript:

Topic 4 Inheritance

Objectives To learn about the concept of inheritance To understand how to inherit and override methods from a superclass To learn about inheritance hierarchies and the general superclass Object To learn about casting objects To learn about the instanceOf operator

Inheritance Inheritance: a mechanism for deriving a new class from an existing one Motivation: Can reuse existing classes Faster, cheaper than writing them from scratch Can organize classes in a hierarchical manner e.g. can go from more general to more specific classes

Example of a Class Hierarchy Vehicle Car Bus SUV Smartcar Van Schoolbus LTCbus Greyhound

Example of a Class Hierarchy Shape 2DShape 3DShape Circle Rectangle Triangle Sphere Cube Tetrahedron Square

Example of Inheritance Suppose we already have a class called BankAccount There are specialized types of bank accounts, such as savings accounts and checking accounts So, we can write new classes called SavingsAccount and CheckingAccount that are derived from the BankAccount class (the base class)

More Examples of Inheritance Base class Derived Classes Rectangle Square Student UndergradStudent GradStudent Loan CarLoan StudentLoan MortgageLoan

Inheritance Terminology The derived new class is called the subclass Also called the child class or derived class It inherits the attributes and methods of the superclass Also called the parent class or base class It can add new attributes or methods for itself, i.e. it can extend the parent class In fact, the Java keyword to make a subclass is extends

Java Example of Inheritance /* Rectangle.java: a class that models a rectangle */ public class Rectangle { private int length; private int width; public Rectangle(int length, int width) { this.length = length; this.width = width; } public int getLength( ) { return length; } // cont’d..

// ..cont’d.. public int getWidth( ) { return width; } public int area( ) { return length*width; public String toString( ) { return "Rectangle: " + "Length(" + length + ") " + "Width(" + width + ")"; } // end of class Rectangle

/ * Square.java: a class that models a square */ public class Square extends Rectangle { // no new attributes need be introduced public Square(int s) { // calls the 2-variable superclass constructor super(s, s); } public int getSide( ) { return getWidth( ); public String toString( ) { return "Square: Side(" + getSide( ) + ")";

Inheriting Visibility public variables and methods: children can access them directly (except the constructor) private variables and methods: children cannot access them directly Why not? this would violate encapsulation protected = may be accessed directly by any class in the same package, or by any subclass So, children can access protected variables and methods of parent directly

The super Reference super is a reserved word used in a derived class to refer to its parent class Allows us to access those members of the parent class that are not inherited Invoking the parent’s constructor: the first line of a child’s constructor should be super(…);

Is-a Relationship The derived class is a more specific version of the original class So, subclass object is of type subclass, but it is also an instance of superclass Example: A Square object is a Rectangle (In fact, a Square object is also an instance of Object, since a class called Object is the parent of every other class (later))

Discussion Why extend an existing class, i.e. why not just change the existing class by adding the new attributes and methods? Can you think of more examples of classes we can model with an inheritance relationship? May not have source code May make existing class too complex Complex classes are harder to build, test, maintain

Example: BankAccount class Suppose we have a class BankAccount with attributes private String accountNumber; private double balance; and public methods deposit, withdraw, printBalance, getBalance, toString What attributes and methods of the BankAccount class can be accessed directly by code in its subclasses?

Example: BankAccount class What new attributes might we have in subclasses SavingsAccount and CheckingAccount? Examples: in SavingsAccount : interestRate in CheckingAccount : transactionCount

Example: BankAccount class Example: BankAccount constructor: public BankAccount(double initialAmount, String accountNumber) { this.balance = initialAmount; this.accountNumber = accountNumber; } CheckingAccount constructor: public CheckingAccount(double initialAmount, String accountNumber) { super(initialAmount, accountNumber); transactionCount = 0; }

Example: BankAccount Class What new methods might we then have in subclasses SavingsAccount and CheckingAccount? In SavingsAccount: addInterest getInterestRate In CheckingAccount: deductFees different deposit – why? different withdraw – why?

Overriding Methods A derived class can define a method with the same signature as a method in the parent class The child’s method overrides the parent’s method Example: methods deposit and withdraw in CheckingAccount override deposit and withdraw of BankAccount Example:method toString in Square overrides toString of Rectangle

Overriding Methods Which method is actually executed at run time? It depends on which object is used to invoke the method Example: Rectangle r = new Rectangle(4,5); Square s = new Square(5); System.out.println(r.toString( )); System.out.println(s.toString( )); Note that a method defined with the final modifier cannot be overridden

More on the super Reference Allows us to invoke a method of the parent class that was overridden in the child class Example: public void deposit (double amount) { balance = balance + amount; } public void deposit(double amount){ transactionCount++; super.deposit(amount); } What would happen if we did not have the super reference here? Method deposit in BankAccount Method deposit in CheckingAccount

Superclass Variables A variable of the superclass type may reference an object of a subclass type Examples (see diagrams next page): Square s = new Square(5); Rectangle r = s; Rectangle t = new Square(6); A variable of the subclass type may not reference an object of the superclass type Why not?

Superclass Variables Square object 5x5 Square s Rectangle r Rectangle t

Type of an Object Note that the type of an object is determined when it is created, and does not change! Examples: … = new Rectangle(2,5); … = new BankAccount(45.65, “12345”); Note that we are not talking about the type of a variable here

Polymorphism Polymorphism : the principle that behaviour can vary, depending on the type of the object being manipulated With inheritance, a variable can refer to objects of different types during its lifetime Example: Rectangle r; r = new Rectangle(2,5); System.out.println(r.toString( )); … r = new Square(2); System.out.println(r.toString( )); What’s printed depends on the actual type of the object (not the type of the variable)

Polymorphism When is it known which method should be invoked? Not until run time! This is called dynamic binding or late binding of the variable to the type of the object Why is this not known at compile time? Example: if ( … ) r = new Rectangle(2,5); else r = new Square(2); System.out.println(r.toString( ));

Dynamic (Late) Binding What happens when a superclass variable references an object of a subclass type, and a method is invoked on that object? Example: Rectangle r = new Square(5); The method must exist in the superclass (or one of its ancestors) or there will be a compiler error Example: System.out.println(r.getSide( )); Not legal: r may not always reference a Square object

Dynamic (Late) Binding If the method also exists in the subclass, the method from the subclass is invoked (this is overriding) Example: what will be printed by System.out.println(r.toString( )); If the method does not exist in the subclass, the method from the superclass is invoked Example: is this legal? System.out.println(r.getWidth( )); - Compiler knows this is OK, runtime system uses the overriding one - Yes, it uses the method from Rectangle – compiler knows this is OK, runtime system uses the one from the parent class because there is no overriding one

Casting Reference Variables Go back to the example: Rectangle r = new Square(5); System.out.println( r.getSide( ) ); This will generate a compiler error (why?) How could we fix it? We can let the compiler know that we intend our variable r to reference a Square object, by casting it to type Square

Review: Casting Primitive Types Recall: we have used casting to convert one primitive type to another Examples: why are we casting here? int i, j, n; n = (int) Math.random( ); double q = i / (double) j; Note that this actually changes the representation from integer to double or vice versa Math.random returns a double

Casting Reference Variables We can also cast from one class type to another within an inheritance hierarchy Fix our previous example by casting: Rectangle r = new Square(5); System.out.println(( (Square) r).getSide( )); The compiler is now happy with our intention that r references a Square object! We can think of this as doing a temporary “type conversion” for the variable

Casting Reference Variables But, what if r did not reference a Square object when casting took place? Rectangle r = new Rectangle(2,5); … System.out.println(( (Square) r).getSide( )); The compiler is happy, but we would get a runtime error (why?)

InstanceOf Operator A safer fix: use the instanceof operator if (r instanceof Square) { System.out.println(((Square)r).getSide( )); } Note that instanceof is an operator, not a method It tests whether the referenced object is an instance of a particular class, and gives the expression the value true or false

Class Hierarchies A derived class can be the parent of classes derived from it A single parent class can have many child classes Siblings: children of the same parent Animal Reptile Bird Mammal Snake Lizard Parrot Horse Bat

Java’s Class Hierarchy A class called Object is at the top of the class hierarchy it is defined in the java.lang package so, by default, any class extends Object Some methods defined in the Object class are: public boolean equals(Object obj); public String toString( ); So, will these methods exist in all classes? yes

Object methods toString method: returns a string containing the object’s class name followed by a unique numeric value (the “hash code” of the object, that says where it is stored in a table of objects) Example: Suppose we had not defined a toString in the Person class. Then the code Person friend = new Person("Snoopy", "Dog", ""); System.out.println(friend); would print: Person@10b62c9 Not very meaningful to us, so we usually override this method in classes we write

Object methods equals method: returns true if the two object references refer to the same object Is this state equivalence or identity equivalence? We often override this method in classes we write, for example if we want equality to mean that the objects hold equal data identity equivalence

Using the Object class A variable of type Object can reference an object of any type! (why?) Example: Object obj = new Rectangle(5,6); So, an array whose elements are of type Object can store any type of object It can even store a mix of object types Example: Object[] stuff = new Object[10]; stuff[0] = new Rectangle(5,6); stuff[1] = new Integer(25); … Because all classes are subclasses of Object

Using the Object class When an element of the array is obtained, it can be cast to its particular (sub)class type, for example: System.out.println(( (Rectangle)stuff[0] ).area( )); We can create a general collection of objects of type Object Example: how would we create a Stack of objects of different types? Create a stack of objects of type Object Then instantiate each one to be of a different type