Programming in the large

Similar documents
Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming

Chapter 7. Inheritance

11/2/09. Code Critique. What goal are we designing to? What is the typical fix for code smells? Refactoring Liskov Substitution Principle

CS-202 Introduction to Object Oriented Programming

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Lecture: Modular Design

Inheritance and Polymorphism

9/10/2018 Programming Data Structures Inheritance

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Test Code Patterns. How to design your test code

Testing and Inheritance. Test Code Patterns. Inheritance-related bugs. Inheritance. Testing of Inheritance. Inheritance-related bugs

Last Time: Object Design. Comp435 Object-Oriented Design. Last Time: Responsibilities. Last Time: Creator. Last Time: The 9 GRASP Patterns

Chapter 6: Inheritance

INHERITANCE. Spring 2019

CSC207 Week 3. Larry Zhang

Design Principles: Part 2

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

11/4/15. Review. Objec&ves. Refactoring for Readability. Review. Liskov Subs&tu&on Principle (LSP) LISKOV SUBSTITUTION PRINCIPLE

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Design Principles: Part 2

CS111: PROGRAMMING LANGUAGE II

Outline. Design Principles: Part 2. e.g. Rectangles and Squares. The Liskov Substitution Principle (LSP) ENGI 5895: Software Design.

Inheritance. Transitivity

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

Object Oriented Software Design - I

Java Magistère BFA

Classes and Inheritance Extending Classes, Chapter 5.2

Inheritance and object compatibility

Java Fundamentals (II)

Accelerating Information Technology Innovation

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Rules and syntax for inheritance. The boring stuff

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

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

Java Object Oriented Design. CSC207 Fall 2014

Programming II (CS300)

CS 251 Intermediate Programming Inheritance

Software Engineering Design & Construction

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

COMP 110/L Lecture 19. Kyle Dewey

Objec&ves. Review. Liskov Subs&tu&on Principle Refactoring for Extensibility. What are reasons that we refactor our code?

ITI Introduction to Computing II

Chapter 10 Classes Continued. Fundamentals of Java

Everything is an object. Almost, but all objects are of type Object!

Software Engineering CSC40232: SOFTWARE ENGINEERING. Guest Lecturer: Jin Guo SOLID Principles sarec.nd.edu/courses/se2017

Principles of Object-Oriented Design

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

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

ITI Introduction to Computing II

Inheritance and Polymorphism

Chapter 5 Object-Oriented Programming

Lesson 14: Abstract Classes and Interfaces March 6, Object-Oriented S/W Development with Java CSCI 3381

CSE 143 Lecture 12 Inheritance

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

CS112 Lecture: Inheritance and Polymorphism

Inheritance, Polymorphism, and Interfaces

Subtypes and Subclasses

CH. 2 OBJECT-ORIENTED PROGRAMMING

CSC9T4: Object Modelling, principles of OO design and implementation

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

CMPSCI 187: Programming With Data Structures. Lecture 6: The StringLog ADT David Mix Barrington 17 September 2012

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

CS111: PROGRAMMING LANGUAGE II

6.170 Recitation #5: Subtypes and Inheritance

Inheritance (Part 5) Odds and ends

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects

CS111: PROGRAMMING LANGUAGE II

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

C12a: The Object Superclass and Selected Methods

CS 61B Discussion 4: Inheritance Fall 2018

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

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

n HW5 out, due Tuesday October 30 th n Part 1: Questions on material we ll cover today n Part 2: BFS using your graph from HW4

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

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

What is Inheritance?

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Programming II (CS300)

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Outline. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Benefits of Subtype Polymorphism. Subtype Polymorphism

Inheritance (continued) Inheritance

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

CS1020: DATA STRUCTURES AND ALGORITHMS I

Conformance. Object-Oriented Programming Spring 2015

Intro. Classes Beginning Objected Oriented Programming. CIS 15 : Spring 2007

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Inheritance (Outsource: )

First IS-A Relationship: Inheritance

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Transcription:

Inheritance 1 / 28

Programming in the large Software is complex. Three ways we deal with complexity: Abstraction - boiling a concept down to its essential elements, ignoring irrelevant details Decomposition - decompose system into packages, classes, functions Reuse - reuse library function in many diferent places Today we introduce another kind of resuse: inheritance 2 / 28

What is inheritance? 3 / 28

What is inheritance? More like genetics... 4 / 28

Inheritance Inheritance: deriving one class from another class. public class Employee {... public class HourlyEmployee extends Employee {... public class SalariedEmployee extends Employee {... Employee is the base class or superclass HourlyEmployee and SalariedEmployee are derived classes or subclasses Subclasses inherit the interface and implementation of their superclass(es) extends is the Java syntax for inheriting from another class Important idea to plant in your head now: subclassing is about concept reuse not merely implementation reuse. For example, HourlyEmployee is-a Employee conceptually. 5 / 28

Superclasses Consider the superclass Employee1: public class Employee1 { private String name; private Date hiredate; public Employee1(String aname, Date ahiredate) { disallownullarguments(aname, ahiredate); name = aname; hiredate = ahiredate; public String getname() { return name; public Date gethiredate() { return hiredate; // and tostring(), etc.... Employee defines the basic information needed to define any employee. 6 / 28

Subclasses The extends clause names the direct superclass of the current class (JLS 8.1.4). Here is a subclass of Employee1, HourlyEmployee1: public class HourlyEmployee extends Employee { public HourlyEmployee(String aname, Date ahiredate) { super(aname, ahiredate); HourlyEmployee inherits all the members of Employee HourlyEmployee can t access private members of Employee directly The super call in the constructor calls Employee s constructor to initialize HourlyEmployee instances The HourlyEmployee concept extends the Employee concept. 7 / 28

super Subtleties If present, an explicit super call must be the first statement in a constructor. If an explicit super call is not present and the superclass has a no-arg constructor, super() will implicitly be the first statement in any constructor If there is no no-arg constructor in a superclass (for example, if the superclass defines other constructors without explicitly defining a no-arg constructor), then subclass constructors must explicitly include a super call. Together, these rules enforce an "inside-out" construction order for objects: the highest superclass piece of an object is initialzed first, followed by the second highest, and so on. 8 / 28

Subclass Constructors Recall our definitions of Employee1 and HourlyEmployee1. public class Employee1 { // The only constructor in Employee public Employee1(String aname, Date ahiredate) { name = aname; hiredate = ahiredate; //... public class HourlyEmployee1 extends Employee1 { public HourlyEmployee1(String aname, Date ahiredate) { super(aname, ahiredate); Would HourlyEmployee1.java compile if we left off the constructor definition? 9 / 28

Inherited Members Given our previous definitions of Employee1 and HourlyEmployee1, we can write code like this (from EmployeeDemo1): DateFormat df = DateFormat.getDateInstance(); HourlyEmployee eva = new HourlyEmployee("Eva L. Uator", df.parse("february 18, 2013")); System.out.println(eva.getName() + " was hired on " + eva.gethiredate()); Note that we didn t have to define getname and gethiredate in HourlyEmployee our current implementation of HourlyEmployee doesn t add anything to Employee 10 / 28

Subclasses Specialize Superclasses We define subclasses to extend or specialize the functionality of their superclasses. Let s add suitable extensions to HourlyEmployee: 1 public class HourlyEmployee2 extends Employee2 { private double hourlywage; private double monthlyhours; public HourlyEmployee(String name, Date hiredate, double wage, double hours) { super(name, hiredate); hourlywage = wage; monthlyhours = hours; public double gethourlywage() { return hourlywage; public double getmonthlyhours() { return monthlyhours; public double getmonthlypay() { return hourlywage * monthlyhours; //... Food for thought: what is the monthly pay rule for ~HourlyEmployee~s? What if an employee works more than 40 hours per week? 1 Employee2 is the same as Employee1, but we ll keep the numbers consistent to avoid confusion. 11 / 28

Access Modifiers Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N Every class has an access level (for now all of our classes are public). Every member has an access level. The defulat access level, no mofifier, is also called "package private." 12 / 28

Access Restrictions Extend to Subclasses private members of superclasses are present in subclasses, but can t be directly accessed. So this won t compile: public class HourlyEmployee2 extends Employee2 { //... public String tostring() { return name + "; Hire Date: " + hiredate + "; Hourly Wage: " + hourlywage + "; Monthly Hours: " + monthlyhours; because name and hiredate are private in Employee2. But their getter methods are public: public class HourlyEmployee3 extends Employee3 { public String tostring() { return getname()+", Hire Date: "+gethiredate() + ", Wage: "+ hourlywage + ", Hours: " + monthlyhours; 13 / 28

Overriding Methods Overriding a method means providing a new definition of a superclass method in a subclass. We ve been doing this all along with tostring and equals, which are defined in java.lang.object, the highest superclass of all Java classes. public class Object { public String tostring() { return getclass().getname() + "@" + Integer.toHexString(hashCode()); public boolean equals(object obj) { return (this == obj); We redefine these on our classes because the default implementation of tostring just prints the class name and hash code (which is the memory address by default). the default implementation of equals just compares object references, i.e., identity equality. What we want from equals is value equality. 14 / 28

@Override Annotation The optional @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. public class Employee2 { //... @Override public String tostring() { return name + "; Hire Date: " + hiredate; Now if our subclass s tostring() method doesn t actually override java.lang.object s (or some other intermediate superclass s) tostring(), the compiler will tell us. 15 / 28

Explicit Constructor Invocation with this What if we wanted to have default values for hourly wages and monthly hours? We can provide an alternate constructor that delegates to our main constructor with this HourlyEmployee3.java: public final class HourlyEmployee3 extends Employee3 { /** * Constructs an HourlyEmployee with hourly wage of 20 and * monthly hours of 160. */ public HourlyEmployee3(String aname, Date ahiredate) { this(aname, ahiredate, 20.00, 160.0); public HourlyEmployee3(String aname, Date ahiredate, double anhourlywage, double amonthlyhours) { super(aname, ahiredate); disallowzeroesandnegatives(anhourlywage, amonthlyhours); hourlywage = anhourlywage; monthlyhours = amonthlyhours; //... 16 / 28

this and super If present, an explicit constructor call must be the first statement in the constructor. Can t have both a super and this call in a constructor. A constructor with a this call must call, either directly or indirectly, a constructor with a super call (implicit or explicit). public final class HourlyEmployee3 extends Employee3 { public HourlyEmployee3(String aname, Date ahiredate) { this(aname, ahiredate, 20.00); public HourlyEmployee3(String aname, Date ahiredate, double anhourlywage) { this(aname, ahiredate, anhourlywage, 160.0); public HourlyEmployee3(String aname, Date ahiredate, double anhourlywage, double amonthlyhours) { super(aname, ahiredate); disallowzeroesandnegatives(anhourlywage, amonthlyhours); hourlywage = anhourlywage; monthlyhours = amonthlyhours; //... 17 / 28

The Liskov Substitution Principle (LSP) Subtypes must be substitutable for their supertypes. Consider the method: public static Date vestdate(employee employee) { Date hiredate = employee.gethiredate(); int vestyear = hiredate.getyear() + 2; return new Date(vestYear, hiredate.getmonth(), hiredate.getday()); We can pass any subtype of Employee to this method: DateFormat df = DateFormat.getDateInstance(); HourlyEmployee eva = new HourlyEmployee("Eva L. Uator", df.parse("february 13, 2013"), 20.00, 200); Date evavestdate = vestdate(eva); We must ensure that subtypes are indeed substitutable for supertypes. 18 / 28

LSP Counterexample A suprising counter-example: public class Rectangle { public void setwidth(double w) {... public void setheight(double h) {... public class Square extends Rectangle { public void setwidth(double w) { super.setwidth(w); super.setheight(w); public void setheight(double h) { super.setwidth(h); super.setheight(h); We know from math class that a square "is a" rectangle. The overridden setwidth and setheight methods in Square enforce the class invariant of Square, namely, that width == height. 19 / 28

LSP Violation Consider this client of Rectangle: public void g(rectangle r) { r.setwidth(5); r.setheight(4); assert r.area() == 20; Client (author of g) assumes width and height are independent in r because r is a Rectangle. If the r passed to g is actually an instance of Square, what will be the value of r.area()? The Object-oriented is-a relationship is about behavior. Square s setwidth and setheight methods don t behave the way a Rectangle s setwidth and setheight methods are expected to behave, so a Square doesn t fit the object-oriented is-a Rectangle definition. Let s make this more formal... 20 / 28

Conforming to LSP: Design by Contract Require no more, promise no less. Author of a class specifies the behavior of each method in terms of preconditions and postconditions. Subclasses must follow two rules: Preconditions of overriden methods must be equal to or weaker than those of the superclass (enforces or assumes no more than the constraints of the superclass method). Postconditions of overriden methods must be equal to or greater than those of the superclass (enforces all of the constraints of the superclass method and possibly more). In the Rectangle-Square case the postcondition of Rectangle s setwidth method: assert((rectangle.w == w) && (rectangle.height == old.height)) cannot be satisfied by Square, which tells us that a Square doesn t satisfy the object-oriented is-a relationship to Rectangle. 21 / 28

LSP Conforming 2D Shapes public interface 2dShape { double area(); public class Rectangle implements 2dShape { public void setwidth(double w) {... public void setheight(double h) {... public double area() { return width * height; public class Square implements 2dShape { public void setside(double w) {... public double area() { return side * side; Notice the use of an interface to define a type. 22 / 28

Interfaces An interface represents an object-oriented type: a set of public methods (declarations, not definitions) that any object of the type supports. Recall the 2dShape interface: public interface 2dShape { double area(); You can t instantiate interfaces. So you must define a class that implements the interface in order to use it. Implementing an interface is similar to extending a class, but uses the implements keyword: public class Square implements 2dShape { public void setside(double w) {... public double area() { return side * side; Now a Square is-a 2dShape. 23 / 28

Interfaces Define a Type public interface 2dShape { double area(); This means that any object of type 2dShape supports the area method, so we can write code like this: public double calctotalarea(2dshape... shapes) { double area = 0.0; for (2dShape shape: shapes) { area += shape.area(); return area; Two kinds of inheritance: implementation and interface inheritance. extending a class means inheriting both the interface and the implementation of the superclass implementing an interface means inheriting only the interface, that is, the public methods 24 / 28

Default Methods in Interfaces Beginning with Java 8 (jdk1.8), interface methods can have default method implementations. These default methods can only reference local variables and static variables defined in the interface or any superinterfaces. 25 / 28

Conflict Resolution for Default Methods Superclasses win. Interfaces clash. 26 / 28

Static Methods in Interfaces 27 / 28

Programming Exercise To get some practice writing classes that use inheritance, write: A class named Animal with: A private instance variable name, with a public getter and setter. (Note: name is a name of an animal, not the animal s species.) A single constructor that takes the name of the Animal A public instance method speak that returns a String representation of the sound it makes. A class named Dog that extends Animal and specializes the speak method appropriately. A Kennel class with a private instance variable dogs that is an array of Dog a single constructor that takes a variable number of single Dog parameters and initializes the dogs instance variable with the constructor s actual parameters. a method soundoff() that prints to STDOUT (System.out) one line for each Dog in dogs that reads "[dog name] says [output of speak method]!", e.g. "Chloe says woof, woof!" We ll review this at the start of the next lecture. 28 / 28