Inheritance (Part 5) Odds and ends

Similar documents
Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance (cont) Abstract Classes

Inheritance, cont. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance (Part 2) Notes Chapter 6

Interfaces. consider an interface for mathematical functions of the form

Java Fundamentals (II)

Object-Oriented Concepts

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

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

INHERITANCE. Spring 2019

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

Java Classes, Inheritance, and Interfaces

Inheritance. Transitivity

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

More about inheritance

Chapter 5 Object-Oriented Programming

EECS2030 Week 7 worksheet Tue Feb 28, 2017

Java Object Oriented Design. CSC207 Fall 2014

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Aggregation and Composition. [notes Chapter 4]

Abstract Classes and Interfaces

Rules and syntax for inheritance. The boring stuff

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Java Magistère BFA

Chapter 10 Classes Continued. Fundamentals of Java

CS-202 Introduction to Object Oriented Programming

CLASS DESIGN. Objectives MODULE 4

Class, Variable, Constructor, Object, Method Questions

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

C12a: The Object Superclass and Selected Methods

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

Programming overview

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

CS1150 Principles of Computer Science Objects and Classes

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

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

The class Object. Lecture CS1122 Summer 2008

Lecture 2: Java & Javadoc

CS313D: ADVANCED PROGRAMMING LANGUAGE

JAVA MOCK TEST JAVA MOCK TEST II

Distributed Systems Recitation 1. Tamim Jabban

Creating an Immutable Class. Based on slides by Prof. Burton Ma

Inheritance and Polymorphism

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

AP CS Unit 6: Inheritance Notes

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

PROGRAMMING LANGUAGE 2

What is Inheritance?

Inheritance (Outsource: )

Distributed Systems Recitation 1. Tamim Jabban

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

public static boolean isoutside(int min, int max, int value)

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

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

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Introduction to Inheritance

Language Features. 1. The primitive types int, double, and boolean are part of the AP

(b) Draw a hash table having 10 buckets. Label the buckets 0 through 9.

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

For this section, we will implement a class with only non-static features, that represents a rectangle

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Making New instances of Classes

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012)

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

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

15CS45 : OBJECT ORIENTED CONCEPTS

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Lecture 10. Overriding & Casting About

Chapter 5. Inheritance

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Methods Common to all Classes

CIS 110: Introduction to computer programming

Chapter 11: Collections and Maps

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

Programming Languages and Techniques (CIS120)

Object Orientated Programming Details COMP360

Programming Languages and Techniques (CIS120)

Inheritance and Polymorphism

COE318 Lecture Notes Week 8 (Oct 24, 2011)

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

Fundamental Java Methods

F I N A L E X A M I N A T I O N

CMSC 132: Object-Oriented Programming II

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

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

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

Computer Science II (20073) Week 1: Review and Inheritance

CS260 Intro to Java & Android 03.Java Language Basics

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

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

Super-Classes and sub-classes

Transcription:

Inheritance (Part 5) Odds and ends 1

Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there is no dynamic dispatch on static methods therefore, you cannot override a static method if you use a variable name instead of the class name to invoke the static method, you get the method that belongs to the declared type of the variable 2

public abstract class Dog { private static int numcreated = 0; public static int getnumcreated() { return Dog.numCreated; public class Mix { private static int nummixcreated = 0; public static int getnumcreated() { return Mix.numMixCreated; notice no @Override public class Komondor { private static int numkomondorcreated = 0; public static int getnumcreated() { return Komondor.numKomondorCreated; notice no @Override 3

public class WrongCount { public static void main(string[] args) { Dog mutt = new Mix(); Dog shaggy = new Komondor(); System.out.println( mutt.getnumcreated() ); System.out.println( shaggy.getnumcreated() ); System.out.println( Mix.getNumCreated() ); System.out.println( Komondor.getNumCreated() ); Dog version Dog version Mix version Komondor version prints 2 2 1 1 4

What's Going On? there is no dynamic dispatch on static methods because the declared type of mutt is Dog, it is the Dog version of getnumcreated that is called because the declared type of shaggy is Dog, it is the Dog version of getnumcreated that is called 5

Hiding Methods notice that Mix.getNumCreated and Komondor.getNumCreated work as expected if a subclass declares a static method with the same name as a superclass static method, we say that the subclass static method hides the superclass static method you cannot override a static method, you can only hide it hiding static methods is considered bad form because it makes code hard to read and understand 6

the client code in WrongCount illustrates two cases of bad style, one by the client and one by the implementer of the Dog hierarchy 1. the client should not have used an instance to call a static method 2. the implementer should not have hidden the static method in Dog 7

8 Using superclass methods

Other Methods methods in a subclass will often need or want to call methods in the immediate superclass a new method in the subclass can call any public or protected method in the superclass without using any special syntax a subclass can override a public or protected method in the superclass by declaring a method that has the same signature as the one in the superclass a subclass method that overrides a superclass method can call the overridden superclass method using the super keyword 9

Dog equals we will assume that two Dogs are equal if their size and energy are the same @Override public boolean equals(object obj) { boolean eq = false; if(obj!= null && this.getclass() == obj.getclass()) { Dog other = (Dog) obj; eq = this.getsize() == other.getsize() && return eq; this.getenergy() == other.getenergy(); 10

Mix equals (version 1) two Mix instances are equal if their Dog subobjects are equal and they have the same breeds @Override public boolean equals(object obj) { // the hard way 11 boolean eq = false; if(obj!= null && this.getclass() == obj.getclass()) { Mix other = (Mix) obj; subclass can call eq = this.getsize() == other.getsize() && public method of this.getenergy() == other.getenergy() && the superclass this.breeds.size() == other.breeds.size() && return eq; this.breeds.containsall(other.breeds);

Mix equals (version 2) two Mix instances are equal if their Dog subobjects are equal and they have the same breeds Dog equals already tests if two Dog instances are equal Mix equals can call Dog equals to test if the Dog subobjects are equal, and then test if the breeds are equal also notice that Dog equals already checks that the Object argument is not null and that the classes are the same Mix equals does not have to do these checks again 12

@Override public boolean equals(object obj) { boolean eq = false; if(super.equals(obj)) { // the Dog subobjects are equal Mix other = (Mix) obj; eq = this.breeds.size() == other.breeds.size() && return eq; subclass method that overrides a superclass method can call the original superclass method this.breeds.containsall(other.breeds); 13

Dog tostring @Override public String tostring() { String s = "size " + this.getsize() + "energy " + this.getenergy(); return s; 14

Mix tostring @Override public String tostring() { StringBuffer b = new StringBuffer(); b.append(super.tostring()); for(string s : this.breeds) b.append(" " + s); b.append(" mix"); return b.tostring(); size and energy of the dog breeds of the mix 15

Dog hashcode // similar to code generated by Eclipse @Override public int hashcode() { final int prime = 31; int result = 1; result = prime * result + this.getenergy(); result = prime * result + this.getsize(); return result; use this.energy and this.size to compute the hash code 16

Mix hashcode // similar to code generated by Eclipse @Override public int hashcode() { final int prime = 31; int result = super.hashcode(); result = prime * result + this.breeds.hashcode(); return result; use this.energy, this.size, and this.breeds to compute the hash code 17

18 Review

Review 1. Inheritance models the relationship between classes. 2. Dog is a of Object. 3. Dog is a of Mix. 4. Can a Dog instance do everything a Mix instance can? 5. Can a Mix instance do everything a Dog instance can? 6. Is a Dog instance substitutable for a Mix instance? 7. Is a Mix instance substitutable for a Dog instance? 19

8. Can a subclass use the private fields of its superclass? 9. Can a subclass use the private methods of its superclass? 10. Suppose you have a class X that you do not want anyone to extend. How do you enforce this? 11. Suppose you have an immutable class X. Someone extends X to make it mutable. Is this legal? 12. What do you need to do to enforce immutability? 20

13. Suppose you have a class Y that extends X. a. Does each Y instance have a X instance inside of it? b. How do you construct the X subobject inside of the Y instance? c. What syntax is used to call the superclass constructor? d. What is constructed first the X subobject or the Y object? e. Suppose Y introduces a brand new method that needs to call a public method in X named xmethod. How does the new Y method call xmethod? f. Suppose Y overrides a public method in X named xmethod. How does the overriding Y method call xmethod? 21

14. Suppose you have a class Y that extends X. X has a method with the following precondition: @pre. value must be a multiple of 2 If Y overrides the method which of the following are acceptable preconditions for the overriding method: a. @pre. value must be a multiple of 2 b. @pre. value must be odd c. @pre. value must be a multiple of 2 and must be less than 100 d. @pre. value must be a multiple of 10 e. @pre. none 22

14. Suppose you have a class Y that extends X. X has a method with the following postcondition: @return A String of length 10 If Y overrides the method which of the following are acceptable postconditions for the overriding method: a. @return A String of length 9 or 10 b. @return The String "weimaraner" c. @return An int d. @return The same String returned by tostring e. @return A random String of length 10 23

15. Suppose Dog tostring has the following Javadoc: /* * Returns a string representation of a dog. * The string is the size of the dog followed by a * a space followed by the energy. * @return The string representation of the dog. */ Does this affect subclasses of Dog? 24

Inheritance Recap inheritance allows you to create subclasses that are substitutable for their ancestors inheritance interacts with preconditions, postconditions, and exception throwing subclasses inherit all non-private features can add new features can change the behaviour of non-final methods by overriding the parent method contain an instance of the superclass subclasses must construct the instance via a superclass constructor 25