1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.

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

1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
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.
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.
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.
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.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
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.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Inheritance Motivation –Code reuse –Conceptual modeling.
Programming Languages and Paradigms Object-Oriented Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
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 and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance CSC 171 FALL 2004 LECTURE 18. READING Read Horstmann, Chapter 11.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Topic 4 Inheritance.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
CHAPTER 11 INHERITANCE. CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
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.
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 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
Chapter 3 Implementing Classes
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Chapter 13 - Inheritance.
Data Structures and Algorithms revision
Inheritance In the real world, objects aren’t usually one-of-a-kind.
Chapter 11 Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism
Lecture Notes – Inheritance (Ch 9-10)
Inheritance in Java.
Chapter 9 Inheritance and Polymorphism
Polymorphism and access control
د.سناء الصايغ الفصل الأول البرمجة الشيئية
Inheritance.
Adapted from Java Concepts Companion Slides
Chapter 11 Inheritance and Polymorphism Part 1
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson

 Hw1  Assigned Tuesday, due next Thursday 9/18

 Java Review/Basics  Types, variables, assignments, expressions  Control flow statements  Methods  Arrays  Array basics  Binary Search Algorithm  Binary Search program  Hw1: number guessing game  ArrayList  OO and Inheritance 3

 Object: entity that you can manipulate in your programs  Data fields: state of an object  Methods: instructions that accesses or modifies the object  Class: construct that defines objects of the same type (set of objects with the same behaviour)  Definition of data fields: properties of defined objects  Definition of methods: behaviours of defined objects ▪ Constructors are special type of methods used to construct and initialize objects from the class

 Software is composed of separate, interchangeable components (modules)  Library of classes that are intended for use by others  Application programming interfaces (APIs) describe the library name and methods  Allows us to reuse code and work with modules of reasonable size

 java.lang.*: standard system library  Math: common mathematical functions ▪ abs(), max(), min(), random(), …  Integer, Double: wrapper classes of primitive types  String, StringBuilder  System ▪ System.in, System.out, System.arraycopy(), …

 java.util.Arrays  array manipulation, such as searching and sorting  java.util.ArrayList  Resizable-array implementation of List  java.util.Scanner  text input scanner

 Textbook libraries (stdlib.jar)  StdIn  StdOut  StdRandom  StdStats  …

Have you heard about the object- oriented way to become wealthy?

 Different types of employees  Hourly employee  Salaried employee  Volunteer  What features are common for all employees?  What features are specific? 10

 A subclass inherits all fields and methods from the superclass  A subclass can also:  Add new fields  Add new methods  Override the methods of the superclass  Superclass’s constructor is not inherited  Unlike fields and methods  They are invoked explicitly or implicitly 11

 Use extends keyword to declare a subclass  Use super keyword to refer to the superclass  To call a superclass constructor ▪ Explicit: super() ▪ Implicit: if no superclass constructor is explicitly invoked, compiler puts super() as the first statement in the constructor  To call a superclass method ▪ super.methodName()  To access a superclass public data field ▪ super.fieldName 12

public class Employee { private String name; // name of the employee public Employee (String n) { name = n; } public Employee () { name = "Unknown"; } public String getName() { return name; } public String toString() { return name;} } public class EmployeeTester { public static void main(String[] args) { Employee e = new Employee(“Homer Simpson”); System.out.println(e); } 13

public class Employee { private String name; // name of the employee public Employee (String n) { name = n; } public Employee () { name = "Unknown"; } public String getName() { return name; } public String toString() { return name;} } public class SalariedEmployee extends Employee { private double weeklySalary; public SalariedEmployee(String n, double salary) { super(n); weeklySalary = salary; } public double earnings() { return weeklySalary; }

 super can be used to call method from superclass 15 public class Employee { private String name; // name of the employee public Employee (String n) { name = n; } public Employee () { name = "Unknown"; } public String getName() { return name; } public String toString() { return name;} } public class SalariedEmployee extends Employee { // … public double printName() { System.out.println(super.getName()); }

 Subclass can modify the implementation of a method defined in the superclass  Called Method overriding  A private method cannot be overridden, because it is not accessible outside its own class  Different from overloading

public class Employee { private String name; // name of the employee public Employee (String n) { name = n; } public Employee () { name = "Unknown"; } public String getName() { return name; } public String toString() { return name;} } public class SalariedEmployee extends Employee { private double weeklySalary; public SalariedEmployee(String n, double salary) { super(n); weeklySalary = salary; } public double earnings() { return weeklySalary; }

public class Employee { private String name; // name of the employee public Employee (String n) { name = n; } public Employee () { name = "Unknown"; } public String getName() { return name; } public String toString() { return name;} } public class SalariedEmployee extends Employee { // Other methods omitted public String toString() { return name + “, “ + earnings(); // wrong, why? } Overriding toString() Method

public class Employee { private String name; // name of the employee public Employee (String n) { name = n; } public Employee () { name = "Unknown"; } public String getName() { return name; } public String toString() { return name;} } public class SalariedEmployee extends Employee { // Other methods omitted public String toString() { return getName() + “, “ + earnings(); // correct } Overriding toString() Method

public class Employee { private String name; // name of the employee // other methods omitted public String getName() { return name; } public String toString() { return name;} } public class SalariedEmployee extends Employee { // Other methods omitted public String toString() { return getName() + “, “ + earnings(); // correct } public class EmployeeTester { public static void main(String[] args) { SalariedEmployee e = new SalariedEmployee(“BestEmployee”, 2000); System.out.println(e); // System.out.println(e.toString()); }

public class Employee { private String name; // name of the employee // other methods omitted public String getName() { return name; } public String toString() { return name;} } public class SalariedEmployee extends Employee { // Other methods omitted public String toString() { return getName() + “, “ + earnings(); // correct } public class EmployeeTester { public static void main(String[] args) { Employee e = new SalariedEmployee(“BestEmployee”, 2000); System.out.println(e); // System.out.println(e.toString()); }

 Fine to convert subclass reference to superclass reference  Need cast to convert from a superclass reference to a subclass reference  This cast is dangerous: if you are wrong, an exception is thrown  Use the instanceof operator to test

object instanceof TypeName Example: if (anObject instanceof Employee) { Employee e = (Employee) anObject;... } Purpose: To return true if the object is an instance of TypeName (or one of its subtypes), and false otherwise

public class EmployeeTester { public static void main(String[] args) { SalariedEmployee s = new SalariedEmployee(“S”, 2000); Employee e = new Employee(“E”); e = s; if (e instanceof SalariedEmployee ) { s = (SalariedEmployee) e; System.out.println (s); // includes salary } // HourlyEmployee h = (HourlyEmployee) e; //exception if (e instanceof HourlyEmployee ) h = (HourlyEmployee) e; System.out.println(e); }

 Method overriding allows Java to invoke method based on a particular object at run- time instead of declared type  Late binding  As opposed to early binding for method overloading

 All classes defined without an explicit extends clause automatically extend Object

 Most useful methods:  String toString()  boolean equals(Object otherObject)  Good idea to override these methods in your classes

 Which of the following statements are true? A. A subclass is a subset of a superclass. B. A subclass is usually created to contain more functions and more detailed information than its superclass. C. "class A extends B" means A is a subclass of B. D. "class A extends B" means B is a subclass of A.

 Which of the following statements are true? A. A method can be overloaded in the same class. B. A method can be overridden in the same class. C. If a method overloads another method, these two methods must have the same signature. D. If a method overrides another method, these two methods must have the same signature.

 Bank Account  getBalance()  deposit()  withdraw()  transfer()  Savings Account  Earns interest that compounds monthly  Checking account  No interest  Small number of free transactions per month, additional transactions are charged a small fee

 Instance fields:  balance (private)  Methods:  BankAccount() (constructor)  BankAccount(double initialBalance) (constructor)  getBalance()  deposit(double amount)  withdraw(double amount)  transfer(double amount, BankAccount other)

 Instance fields:  balance (inherited from BankAccount )  transactionCount (new to CheckingAccount )  Methods:  CheckingAccount() (constructor)  getBalance() (inherited from BankAccount )  deposit(double amount) (overrides BankAccount method) – need to update the transaction count  withdraw(double amount) (overrides BankAccount method) – need to update the transaction count  deductFees() (new to SavingsAccount )

public void deposit(double amount) { transactionCount++; // Now to add amount to balance balance = balance + amount; }

public void deposit(double amount) { transactionCount++; // How to add amount to balance deposit(amount); }

public void deposit(double amount) { transactionCount++; // How to add amount to balance super.deposit(amount); // correct }

 Instance fields:  balance (inherited from BankAccount )  interestRate (new to SavingsAccount )  Methods:  SavingsAccount() (constructor)  getBalance() (inherited from BankAccount )  deposit(double amount) (inherited from BankAccount method)  withdraw(double amount) (inherited BankAccount method)  addInterest() (new to SavingsAccount )

 BankAccountTester.java  What’s the output?  Hint: in the transfer method, depending on types of other, different versions of withdraw and deposit are invoked - polymorphism