Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Similar documents
COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

Inheritance & Polymorphism. Object-Oriented Programming

Object-Oriented Programming More Inheritance

Java Session. Day 2. Reference: Head First Java

Software Development (cs2500)

Inheritance & Polymorphism

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

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007

Object-Oriented ProgrammingInheritance & Polymorphism

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

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

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

What is Inheritance?

Chapter 14 Abstract Classes and Interfaces

Lecture 2 and 3: Fundamental Object-Oriented Concepts Kenneth M. Anderson

First IS-A Relationship: Inheritance

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

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel)

Programming II (CS300)

More Relationships Between Classes

Inheritance and Polymorphism in Java

CSA 1019 Imperative and OO Programming

Rules and syntax for inheritance. The boring stuff

Inheritance (Outsource: )

Practice for Chapter 11

Inheritance, Polymorphism, and Interfaces

Polymorphism. Arizona State University 1

CS111: PROGRAMMING LANGUAGE II

CMSC 132: Object-Oriented Programming II

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

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

Java Magistère BFA

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance and Polymorphism

COMP 250 Fall inheritance Nov. 17, 2017

Inheritance. Transitivity

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

ECE 122. Engineering Problem Solving with Java

INHERITANCE. Spring 2019

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

Object Oriented Programming. Java-Lecture 11 Polymorphism

Abstract Classes and Interfaces

Inheritance (Part 2) Notes Chapter 6

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

Inheritance, polymorphism, interfaces

Java Object Oriented Design. CSC207 Fall 2014

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

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

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

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

Logistics. Final Exam on Friday at 3pm in CHEM 102

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 4 09/03/2009

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

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

Inheritance and Interfaces

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

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

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

Java Fundamentals (II)

type conversion polymorphism (intro only) Class class

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

UML & OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 3 08/30/2011

Chapter 5 Object-Oriented Programming

COMP 110/L Lecture 20. Kyle Dewey

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

Programming II (CS300)

OVERRIDING. 7/11/2015 Budditha Hettige 82

C18a: Abstract Class and Method

Inheritance in Java. Produced by: Eamonn de Leastar Dr. Siobhán Drohan

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

PROGRAMMING LANGUAGE 2

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

AP CS Unit 6: Inheritance Notes

OLLSCOIL NA heireann THE NATIONAL UNIVERSITY OF IRELAND, CORK. COLAISTE NA hollscoile, CORCAIGH UNIVERSITY COLLEGE, CORK

Java How to Program, 8/e

Building custom components IAT351

Inheritance. CSE 142, Summer 2002 Computer Programming 1.

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Self-review Questions

C++ Important Questions with Answers

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

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

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

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

The class Object. Lecture CS1122 Summer 2008

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

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces

CMSC 132: Object-Oriented Programming II

Create a Java project named week10

CS260 Intro to Java & Android 03.Java Language Basics

Object-Oriented Programming

Object Fundamentals Part Two. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 3 09/01/2009

UML & OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 3 09/04/2012

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

Transcription:

Object Oriented Programming Part II of II Steve Ryder Session 8352 JSR Systems (JSR) sryder@jsrsys.com

New Terms in this Section API Access Modifier Package Constructor 2

Polymorphism Three steps of object declaration and assignment 1.Declare a reference variable 1 2 3 Dog mydog = new Dog(); 2.Create an object 3.Link the object and the reference 3

Polymorphism Power references The reference and the object can be different Animal mydog = new Dog(); 4

Polymorphic Arrays Power references allow you to make polymorphic arrays Animal [ ] animals = new Animal[5]; animals[0] = new Dog(); animals[1] = new Cat(); for (int I = 0; I < animals.length; I ++) { animals[i].eat(); animals[i].roam(); } 5

Arguments/Return Types You can use polymorphic arguments and return types. class Vet { public void giveshot(animal a) { //do vet stuff a.makenoise; } } 6

Arguments/Return Types You can use polymorphic arguments and return types. class Vet { public void giveshot(animal a) { //do vet stuff a.makenoise; } } Any Animal subclass can be passed in as an argument to the Vet class. 7

Arguments/Return Types You can use polymorphic arguments and return types. class Vet { public void giveshot(animal a) { //do vet stuff a.makenoise; } } Invokes the method of the animal type (subclass) passed in as an argument 8

Review A reference variable can be thought of as a remote control that controls the behavior and state of an object. Dog mydog = new Dog(); You can set the reference variable to a more generic type than the object it controls. Animal a = new Dog(); You can define an argument and/or return type used by a method as a more generic type but pass/return the more specific type. public void giveshot(animal a) 9

Limits to Subclassing How many levels deep can you go when designing subclasses? Most Java API inheritance hierarchies are wide but not deep. Most stay within one to two levels deep. It s good practice, generally, to keep your hierarchy shallow but there is no hard limit that you are likely to encounter. 10

Do-overs a.k.a. Method Overriding If you are unable to change the code for a given class, yet you need to change how it works, you can extend a bad class and override the method with new, better code. 11

Do Not Extend There are three things that can prevent a class from being extended, or subclassed: 1. There is no public declaration. 2. The class has the a final access modifier. 3. The class has only private constructors. 12

Why use final? Make a class final only if you need the security of knowing that all methods will work as originally written. Make a method final if you want to protect only certain methods within a class. 13

Rules for Overriding When overriding a method from a superclass, you are, in effect, agreeing to a contract. Here are the rules for overriding a method: Arguments and return types must be the same. Access levels on the subclass must be equal to or more lenient than the superclass. 14

Overloading Overloading is having two methods with the same name but different arguments. Overloaded methods have great flexibility: 1. Return types can be different as long as the arguments are different types. 2. The return type can not be the only thing changed. 3. You can vary the access levels in any manner. 15

Review Try to keep class hierarchies one to two levels deep. Method Overriding can be used as a do-over when you can not change existing code. You can not extend a class that has no public declaration, is declared final, or has private constructors. Use final to secure a class when you don t want any of the class to change. Use final to secure a method when you only want certain methods to remain unchanged. Overriding = agreeing to the superclass contract. Arguments and return types must be the same. Access levels must be the same or less restrictive. Overloading = two or more methods with same name but different arguments (in type or number) and/or return types. 16

Serious Polymorphism Abstract classes Abstract methods Object class Arraylist Interfaces 17

Abstract Classes Keep duplicate code to a minimum. Override generic methods. Flexible because of Animal subtypes that can be designed in the future and used in any method expecting an Animal object as an argument. Creates a common protocol for all animals that are related to the Animal superclass. 18

Abstract Classes Sample Animal class hierarchy Animal Canine Hippo Reptile Wolf 19

Abstract Classes Given the class design on the previous slide, the following declarations are valid: Animal ahippo = new Hippo(); Canine awolf = new Wolf(); Wolf awolf = new Wolf(); But what about this? Animal anim = new Animal(); Greep! Greep! What would an Animal object look like? 20

Abstract Classes The Animal class is necessary for the inheritance and polymorphism we ve been covering. However Programmers should only be able to instantiate the more concrete subclasses like Wolf or Hippo because those have shapes, sizes, and behaviors that are well-defined. To stop a class from being instantiated, make the class abstract. abstract class Animal abstract class Canine extends Animal 21

Abstract Methods An abstract method must be overridden. An abstract method has no body. public abstract void eat(); If you declare a method as abstract, you must declare the class abstract as well. 22

Abstract Methods What can an abstract method be used for? The point of an abstract method is that even without any actual code, you still have defined part of the protocol for a group of subclasses. 23

Abstract Methods What if there are two abstract classes in the hierarchy? A subclass can pass the buck. If Animal and Canine are both abstract, the first concrete class to extend Canine must implement all abstract methods from both Animal and Canine. 24

Review Abstract classes and methods are useful for keeping duplicate code to a minimum while maintaining a protocol for a group of classes. An abstract class can not be instantiated. This forces the programmer to instantiate only the more specific (or concrete) subclasses. Abstract methods define the behaviors that all subclasses must have. Each subclass has its own unique way to implement the behaviors. The first concrete class in the hierarchy (Wolf from Canine and Animal) must implement all methods from both Canine and Animal. 25

The Mother of all Classes class Object Every class in Java extends the Object class. Any class that does not explicitly extend another class implicitly extends Object. 26

The Dot Operator The Dot operator (.) gives you access to an object s state and behavior. //Make a new Object Dog d = new Dog(); //Call the Dog s bark method d.bark(); //Set the size of the Dog d.size = 40; 27

Object Class Methods Three methods available to every object. 1. equals(object o) 2. getclass() 3. hashcode() 28

equals() Tests if one object is equal to another object. Object object1 = new Object; Object object2 = new Object; if object1.equals(object2) { System.out.println( True ); }else{ System.out.println( False ); } 29

getclass() Returns the class from which a particular object was instantiated Cat c = new Cat(); System.out.println(c.getClass); Displays class Cat 30

hashcode() Returns the hashcode (or unique id from memory) for the object. Cat c = new Cat(); System.out.println(c.hashCode); Displays, for example: 8202111 31

The Inner Object When you instantiate a new object, you get a single object in memory. The new object is wrapped around the Object class. new Snowboard(); Object Snowboard 32

Review All objects that do not explicitly extend another class implicitly extend the Object class. There are a number of useful methods in the Object class that can be used with any object -- equals(), getclass(), hashcode() are a few examples. Each new object is considered a single object wrapped around an inner Object class. 33

Objects in an ArrayList Objects come out of an ArrayList acting like they are generic objects. ArrayList Object Object Object 34

Objects in an ArrayList 1 2 3 4 ArrayList al = new ArrayList(); Tiger t = new Tiger(); al.add(t); //Make Tiger in ArrayList growl 1) Instantiate ArrayList object 2) Instantiate Tiger object 3) Add Tiger object to ArrayList 35

Objects in an ArrayList 1 2 3 4 ArrayList al = new ArrayList(); Tiger t = new Tiger(); al.add(t); //Make Tiger in ArrayList growl Can you call the Tiger s makenoise method here? No. Only the methods in the Object class are available at this point. 36

Casting an Object Reference Back to its Real Type 1 2 3 Object o = al.get(index); Tiger t = (Tiger) o; t.makenoise(); 1) Get the object from ArrayList 2) Generic object o is casted to a Tiger object and assigned to the t reference variable 3) The makenoise() method of the Tiger class is called 37

Review Objects go into an ArrayList as the specified type but come out as generic objects. To access the methods of the specific type, you must cast the object to the specific object. 38

Pet Shop Program What if the Dog class that was written for any type of dog was needed as a pet in another program? The Dog class would need new pet-oriented methods such as play(), sit(), rollover(), etc.. Let s review three design options to make this happen 39

Pet Shop Design Option 1 Put pet methods in Animal class. Pros All Animals instantly inherit pet behaviors. We won t have to touch existing Animal subclasses. Any Animal subclass created in the future will get the pet methods. Any program wanting to treat animals as pets can use the Animal class as a polymorphic argument or return type. Cons ALL animals inherit pet behaviors even lions, tigers, and bears oh, my! There are sure to be changes required to the subclasses like Dog and Cat because they would implement pet behaviors very differently. 40

Pet Shop Design Option 2 Put pet methods in the Animal class but make the methods abstract, forcing the subclasses to override them. Pros All the benefits of option1 are realized plus there would be no unwanted animals with pet attributes. The abstract methods that must be overridden can be empty. Cons Every subclass of Animal would have to have pet methods even if they aren t needed. The existence of Pet methods in the subclasses would be misleading as pet behaviors would be expected from those methods. 41

Pet Shop Design Option 3 Put the pet methods only in the classes where they belong. Pros The pet methods are only where they belong. Cons There is no way for other programmers to know what the protocol for establishing or using pet behaviors and no way for the compiler to make sure pet-like methods are implemented correctly. The Animal class could not be used as the polymorphic type because the compiler will not let you call a pet method on an Animal reference. 42

Pet Shop Best Design Create two superclasses: Animal and Pet. Give the Pet class all of the Pet methods. Have subclasses that should use Pet methods extend both the Animal and Pet classes. 43

Deadly Diamond of Death Multiple Inheritance is not allowed in Java because of the possible creation of the Deadly Diamond of Death. DigitalRecorder int I burn() int I burn() CDBurner int I DVDBurner burn() ComboDrive 44

Interfaces Java provides a tool called an interface because you can not extend two classes. An interface is a class with the keyword interface as part of the class declaration. In an interface, all methods are abstract. All subclasses (of the interface) must implement the interface s methods. 45

Interfaces To define an interface public interface Pet { } To implement an interface public class Dog extends Animal implements Pet { } 46

Interfaces Interfaces are extremely flexible because You can use interfaces instead of concrete subclasses as arguments and return types. The classes that implement an interface can come from any inheritance tree. This allows you to treat an object by the role it plays and not the class type used to instantiate it. A class can implement multiple interfaces. 47

Review You can not extend two classes in Java. An interface allows multiple inheritance without the Deadly Diamond of Death. An interface has all abstract methods. A class can inherit multiple interfaces. 48