Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Similar documents
Inheritance (P1 2006/2007)

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy

Intro to Computer Science 2. Inheritance

Abstract Classes and Interfaces

Handout 9 OO Inheritance.

Introduction to Inheritance

Polymorphism. return a.doublevalue() + b.doublevalue();

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Software and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London

CMSC 132: Object-Oriented Programming II

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Chapter 10 Inheritance. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

CS-202 Introduction to Object Oriented Programming

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

Inheritance and Subclasses

CHAPTER 10 INHERITANCE

Lesson 35..Inheritance

Object Oriented Programming. Java-Lecture 11 Polymorphism

Check out Polymorphism from SVN. Object & Polymorphism

Programming II (CS300)

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Programming II (CS300)

Java Magistère BFA

Polymorphism and Interfaces. CGS 3416 Spring 2018

Inheritance and Polymorphism

Objects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017

INHERITANCE. Spring 2019

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Java Object Oriented Design. CSC207 Fall 2014

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance. Inheritance

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 14 Abstract Classes and Interfaces

Inheritance and Interfaces

C# Programming for Developers Course Labs Contents

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Inheritance -- Introduction

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Inheritance. Transitivity

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

Inheritance. The Java Platform Class Hierarchy

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

CSC Inheritance. Fall 2009

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Chapter 13 Abstract Classes and Interfaces

More about inheritance

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

Practice for Chapter 11

Principles of Software Construction: Objects, Design, and Concurrency

Inheritance: Definition

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

VIRTUAL FUNCTIONS Chapter 10

Inheritance (Part 5) Odds and ends

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CMSC 132: Object-Oriented Programming II

Java Fundamentals (II)

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

ITI Introduction to Computing II

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

ITI Introduction to Computing II

ITI Introduction to Computing II

Inheritance and Interfaces

CN208 Introduction to Computer Programming

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

C12a: The Object Superclass and Selected Methods

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Encapsulation. Mason Vail Boise State University Computer Science

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

ITI Introduction to Computing II

Inheritance, Polymorphism, and Interfaces

Motivations. Chapter 13 Abstract Classes and Interfaces

index.pdf January 21,

Chapter 5 Object-Oriented Programming

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

More On inheritance. What you can do in subclass regarding methods:

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

Inheritance, polymorphism, interfaces

Super-Classes and sub-classes

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Chapter 13 Abstract Classes and Interfaces

Making New instances of Classes

CLASS DESIGN. Objectives MODULE 4

Abstract and final classes [Horstmann, pp ] An abstract class is kind of a cross between a class and an interface.

Inheritance (continued) Inheritance

Inheritance (Outsource: )

Programming in C# Inheritance and Polymorphism

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

The class Object. Lecture CS1122 Summer 2008

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

Lecture 4: Extending Classes. Concept

Principles of Software Construction: Objects, Design, and Concurrency. Part 1: Designing Classes. Design for Reuse School of Computer Science

CIS 110: Introduction to computer programming

Transcription:

Inheritance & Abstract Classes 15-121 Margaret Reid-Miller

Today Today: Finish circular queues Exercise: Reverse queue values Inheritance Abstract Classes Clone 15-121 (Reid-Miller) 2

Object Oriented Programming Inheritance 15-121 (Reid-Miller) 3

Inheritance Inheritance in object-oriented programming languages enables you to define a new class based on an existing class. The idea is to refine an existing class to derive a new class, by adding new fields, and adding new methods or redefining existing methods. It enables code reuse because the new class inherits the all the fields and methods of the existing class. The original class is called the superclass and the class based on the superclass class is called the subclass. 15-121 (Reid-Miller) 4

Inheritance Every class inherits (implicitly) from the Object class in Java. Every class is-a Object There are no fields in Object, but there are method such as tostring. All classes are arranged in a hierarchy (a tree) with Object at the top of the hierarchy. 15-121 (Reid-Miller) 5

Superclasses & Subclasses Object is-a Shape Circle Polygon Triangle Rectangle Can inherit from at most one class. Square 15-121 (Reid-Miller) 6

Inheritance keywords A class that extends another class is a subclass that inherits all fields and methods (but not constructors) of the superclass. The subclass has direct access to all fields that are public and protected. The subclass can override the definitions of inherited methods with new implementations (using the same signature) and can access overridden methods using the super keyword. 15-121 (Reid-Miller) 7

Example: A superclass public class BankAccount { private double balance; automatically inherits from Object if no other superclass is specified public BankAccount() {... public BankAccount(double initbalance) {... public void deposit(double amount) {... public void withdraw(double amount) {... public double getbalance() {... 15-121 (Reid-Miller) 8

Example: A subclass public class SavingsAccount extends BankAccount { private double interestrate; The subclass need only define the fields and methods that distinguishes the subclass from the superclass. 15-121 (Reid-Miller) 9

Inheritance: extends Fields of a subclass comes for two sources: It inherits all the fields of all its ancestor classes. It can define additional fields of its own. That is, objects of the subclass may store more data than objects of the superclass. Methods of a subclass can be defined as follows: inherits from the ancestor classes automatically, add instructions to inherited methods, override (redefine) inherited methods, or define new methods, possibly overloading inherited methods. 15-121 (Reid-Miller) 10

Constructors public SavingsAccount(double initrate, double initbalance) { super(initbalance); interestrate = initrate; public SavingsAccount(double initrate) { super(); interestrate = initrate; 15-121 (Reid-Miller) 11

New method public void addinterest() { deposit(getbalance()*interestrate); 15-121 (Reid-Miller) 12

Another way: protected In BankAccount: protected double balance; In SavingsAccount: public void addinterest() { deposit(balance*interestrate); 15-121 (Reid-Miller) 13

Field and Method visibility Classes (and their parts) have visibility modifiers: public: accessible to everyone protected: inside package, inside class, inside subclass package-private (default, no modifier used): inside package, inside class private: accessible only within the class 15-121 (Reid-Miller) 14

Overriding methods A subclass can redefine inherited methods if the inherited method does not do what the subclass needs. A method overrides the inherited method if it has the same signature and return type as the parent s definition. An object of the superclass will have the superclass method definition. An object of a subclass will have the subclass method definition; the superclass definition of the method is not visible to the object of a subclass. 15-121 (Reid-Miller) 15

Overriding A savings account subtracts a fee of $10 for withdrawals over $1000. We need to override the withdraw method and provide a new implementation that is appropriate. public void withdraw(double amount) { if (amount > 1000.0) super.withdraw(amount + 10.0); else super.withdraw(amount); same return type same signature 15-121 (Reid-Miller) 16

Overriding Object methods Classes inherit methods from the Object class. These methods typically do not work properly for our specific subclasses so we must override them. public boolean equals(object obj) { SavingsAccount other = (SavingsAccount)obj; return this.interestrate == other.interestrate && this.balance == other.balance; (assuming balance is protected in the BankAccount class) 15-121 (Reid-Miller) 17

Casting In the equals method, we used the following casting: SavingsAccount other = (SavingsAccount)obj; What if obj isn't a SavingsAccount? A ClassCastException is generated during runtime. We can use the instanceof operator to check the object's actual type during runtime. 15-121 (Reid-Miller) 18

instanceof example public boolean equals(object obj) { if (obj instanceof SavingsAccount) { SavingsAccount other = (SavingsAccount)obj; return return false; this.interestrate == other.interestrate && this.balance == other.balance; 15-121 (Reid-Miller) 19

Overriding Object methods Methods you should override: public boolean equals(object obj) Compares this object with the specified object by comparing the references only. public String tostring() Returns the class name + "@" + the hexadecimal representation of the object's hashcode. public int hashcode() Calculates the hashcode of this object based on its reference only. 15-121 (Reid-Miller) 20

Polymorphism BankAccount acct; acct = new BankAccount(15111.0); acct.withdraw(2000.0); System.out.println(acct.getBalance()); acct = new SavingsAccount(15111.0); acct.withdraw(2000.0); System.out.println(acct.getBalance()); The same statement calls two different methods. 15-121 (Reid-Miller) 21

Interfaces (review) A Java interface (not a GUI) is a means for defining specifications for behaviors that are common across classes that are not directly related by inheritance. public interface Comparable<T> { int compareto(t obj); abstract method(s) no fields An interface cannot be instantiated directly: WRONG! Comparable<String> s = new Comparable<String>(); 15-121 (Reid-Miller) 22

Using Interfaces Any class that provides the behavior(s) specified in an interface must implement that interface and provide implementations for the methods specified. public class BankAccount implements Comparable<BankAccount> {... public int compareto(bankaccount other) {... // provide implementation 15-121 (Reid-Miller) 23

Abstract Classes An abstract class can have abstract methods like interfaces, but can also have fields. Abstract classes can also have concrete (implemented) methods. An abstract class cannot be instantiated directly. Subclasses of an abstract class must provide implementations of the abstract methods specified in the abstract class definition. Abstract classes can have constructors that initialize fields defined in the abstract class. 15-121 (Reid-Miller) 24

Abstract Class Example public abstract class Vehicle { private int speed; private String manufacturer;... public int getspeed { return speed; public String getmanufacturer { return manufacturer; public abstract double computetax();... 15-121 (Reid-Miller) 25

Abstract Class Example (cont'd) public class Truck extends Vehicle { private int numwheels;... public double computetax() { return 10.0 * numwheels;... 15-121 (Reid-Miller) 26

Correct Usage Interfaces: String s = new String("Pittsburgh"); Comparable<String> s = new String("Erie"); Abstract classes: Truck mytruck = new Truck("Good Humor"); Vehicle myride = new Truck("Ryder"); 15-121 (Reid-Miller) 27

Comparison Actual Class Abstract Class Interface Instances can be created Y N N Can define fields and methods Y Y N Can define constants Y Y Y Number of these a class can extend 0 or 1 0 or 1 0 Number of these a class can implement 0 0 any number Can extend another class Y Y N Can declare abstract methods N Y Y Can declare variables of this type Y Y Y 15-121 (Reid-Miller) 28

Copying data public class Person { String name; int number; CalendarDate birthday; Person p1 = new Person("Roethlisberger", 7, new CalendarDate(3, 2, 1982); 15-121 (Reid-Miller) 29

Copying data Person p2 = p1; p1 name "Roethlisberger" p2 number 7 birthday month day year 3 2 1982 15-121 (Reid-Miller) 30

Cloning: Shallow Copy In the Person class: public Object clone() { Object newobj = new Person(name, number, birthday); return newobj; 15-121 (Reid-Miller) 31

Cloning: Shallow Copy Person p2 = (Person)p1.clone(); p1 p1 name number 7 "Roethlisberger" birthday name month 3 p2 number 7 day 2 birthday year 1982 15-121 (Reid-Miller) 32

Cloning: Deep Copy In the Person class: public Object clone() { try { Person newperson = (Person)super.clone(); newperson.birthday = (CalendarDate)birthday.clone(); return newperson; catch (CloneNotSupportedException e) { throw new InternalError(); Object has a clone method that performs the shallow copy. CalendarDate must also have a clone method. 15-121 (Reid-Miller) 33

Cloning: Deep Copy In the CalendarDate class: public Object clone() { try { CalendarDate newdate = (CalendarDate)super.clone(); return newdate; catch (CloneNotSupportedException e) { throw new InternalError(); 15-121 (Reid-Miller) 34

Cloning: Deep Copy The method Object.clone will generate a CloneNotSupportedException if it is called in a class that does not implement the Cloneable interface. Therefore: public class Person implements Cloneable {... public class CalendarDate implements Cloneable {... 15-121 (Reid-Miller) 35

Cloning: Deep Copy Person p2 = (Person)p1.clone(); "Roethlisberger" p1 name number 7 month day 3 2 birthday year 1982 name month 3 p2 number 7 day 2 birthday year 1982 15-121 (Reid-Miller) 36

Cloning: Deep Copy Strings are immutable p2.setname("big Ben"); "Roethlisberger" p1 name number 7 month day 3 2 birthday year 1982 name month 3 p2 number 7 day 2 birthday year 1982 "Big Ben" 15-121 (Reid-Miller) 37