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

Similar documents
Implements vs. Extends When Defining a Class

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

OBJECT ORİENTATİON ENCAPSULATİON

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

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Java Object Oriented Design. CSC207 Fall 2014

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

CIS 110: Introduction to computer programming

Inheritance and Polymorphism

CMSC 132: Object-Oriented Programming II. Inheritance

Inheritance (continued) Inheritance

Example: Count of Points

CS111: PROGRAMMING LANGUAGE II

Java Magistère BFA

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

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

ITI Introduction to Computing II

ITI Introduction to Computing II

Inheritance Motivation

Lecture 4: Extending Classes. Concept

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Exercise: Singleton 1

What is Inheritance?

First IS-A Relationship: Inheritance

Abstract Classes and Interfaces

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

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

INHERITANCE. Spring 2019

CS-202 Introduction to Object Oriented Programming

More Relationships Between Classes

Inheritance. Transitivity

JAVA MOCK TEST JAVA MOCK TEST II

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

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

Inheritance, and Polymorphism.

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

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

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

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

Practice for Chapter 11

Advanced Placement Computer Science. Inheritance and Polymorphism

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

Inheritance and Polymorphism

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

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

Inheritance and Interfaces

What are the characteristics of Object Oriented programming language?

ECE 122. Engineering Problem Solving with Java

C08: Inheritance and Polymorphism

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

Rules and syntax for inheritance. The boring stuff

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

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

CMSC 132: Object-Oriented Programming II

8. Polymorphism and Inheritance

Week 5-1: ADT Design

Methods Common to all Classes

Inheritance, polymorphism, interfaces

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

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Making New instances of Classes

Inheritance and object compatibility

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

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

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

Lecture 18 CSE11 Fall 2013 Inheritance

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

25. Generic Programming

The class Object. Lecture CS1122 Summer 2008

Chapter 10 Classes Continued. Fundamentals of Java

CH. 2 OBJECT-ORIENTED PROGRAMMING

CST242 Object-Oriented Programming Page 1

Polymorphism. Arizona State University 1

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I

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

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

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

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

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

Check out Polymorphism from SVN. Object & Polymorphism

Chapter 14 Abstract Classes and Interfaces

Programming Languages and Techniques (CIS120)

VIRTUAL FUNCTIONS Chapter 10

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

C09: Interface and Abstract Class and Method

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

Lecture Notes Chapter #9_b Inheritance & Polymorphism

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

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

Programming Exercise 14: Inheritance and Polymorphism

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

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

Java Fundamentals (II)

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

Transcription:

Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006 2006 Univeristy of Maryland

Project #7 Assigned! Project due Wednesday, 11/29 at 11 pm Project is closed You must complete the project by yourself Assistance can only be provided by teaching assistants (TAs) and instructors You must not look at other students' code Start now! Read entire assignment from beginning to end before starting to code Check out assignment now from CVS Follow the instructions exactly, as much of grading is automated 1

Inheritance Recap Inheritance occurs when one class (derived class, subclass) is defined from another class (base / parent class, superclass). To derive a class D from a base class B, use: public class D extends B { Derived class inherits all instance variables, methods from base class. It can also define new instance variables, methods In derived-class constructor, super( ) can be used to invoke constructor from base class Derived class can explicitly refer to entities from base class using super, e.g. super.tostring( ) Polymorphism: object in derived class can be used anywhere base class is expected (a Student is a Person!) Derived class can override base-class methods (and variables) final can be used to disallow overriding Java uses late binding to determine which version of method to use protected modifier exposes declarations to subclasses (and package) 2

Inheritance Recap (cont.) All objects are derived (directly or indirectly) from Object Late binding and inheritance allows you to create polymorphic variables When a method in a base class is not provided, the method and class are said to be abstract. Abstract methods may be implemented in (concrete) derived classes Run-time information about class / type information of objects can be obtained using getclass() method and instanceof operator Upcasting of object to superclass type is always safe and done automatically Downcasting may not be safe, depending on actual class object belongs to at run-time. Safe downcasting can be done using instanceof 3

Abstract Classes vs. Interfaces Interfaces seem like pure abstract classes Interfaces contain function prototypes These are similar to abstract methods Abstract classes permit some methods to be defined and shared Advantage: abstract classes A given class can match multiple interfaces, but can only inherit from one class Advantage: interfaces Which to use? Code to share: use abstract classes Otherwise: interfaces 4

University Person Recap extends Person class: Student instance variables: int admityear double gpa methods: Student( ) [various] int getadmityear( ) double getgpa( ) void setadmityear( int ) void setgpa( double ) String tostring( ) boolean equals( Student ) class: Person instance variables: String name String idnum methods: Person( ) [various] String getname( ) String getidnum( ) void setname( String ) void setidnum( String ) String tostring( ) boolean equals( Person ) extends Person class: Faculty instance variables: int hireyear methods: Faculty( ) [various] int hireyear( ) void sethireyear( int ) String tostring( ) boolean equals( Student ) 5

equals() Reconsidered Recall definition of equals() in Person public boolean equals (Person p) { return name.equals(p.getname()) && idnum.equals(p.getidnum()); in Student public boolean equals( Student s ) { return super.equals(s) && admityear == s.admityear && gpa == s.gpa; What does following do? public static void main (String[] args) { Student bob = new Student ("R. Goode", "234-56-7890", 1998, 3.89); Faculty bob2 = new Faculty ("R. Goode", "234-56-7890", 2005); System.out.println (bob.equals (bob2)); true is printed! 6

Why? bob is-a Student bob2 is-a Faculty Both are-a Person bob2 cannot be cast to Student bob2 can be cast to Person So the Person version of equals() in bob is called (overloading!) But how can objects in two different classes be equal? 7

A Better equals() Take Object as input Check for non-null-ness of input Check that class is correct Then do other checks For example in Person: public boolean equals (Object o) { if (o == null) return false; else if (o.getclass()!= getclass()) return false; else { Person p = (Person)o; return name.equals(p.getname()) && idnum.equals(p.getidnum()); Similar improvements can be made to Student, Faculty Now bob.equals(bob2) returns false 8

Copy Constructors Reconsidered Copy constructors used to make copies of objects Recall copy constructor for Person public Person( Person p ) { name = p.name; idnum = p.idnum; Does this always do what we want? 9

Deep Copying of a Person Array public static Person[] deepcopy (Person[] a) { Person[] r = new Person[a.length]; for (int i=0; i < a.length; i++) r[i] = new Person(a[i]); return r; What happens if a contains Student, Faculty objects? They are converted into Person objects; extra info lost Consider: a[0] = new Student ( BG, 123-45-6789,2005,3.2); a[1] = new Faculty ( FS, 111-11-1111,2003); deepcopy(a) returns r: r[0] is Person object with name== BG, idnum == 123-45-6789 r[1] is Person object with name== FS, idnum == 111-11-1111 Why? Person copy constructor creates object in class Person Often, in copying, we want to preserve original class of copied object How to do this 10

A Better Way to Do Copying In addition to copy constructors in classes include copying capability in objects To make a copy of an object, call object s copy method This way, new copy will be in same class as original object (late binding) This object-based approach to copying is called cloning Object class includes clone method that can be overridden 11

Defining clone in Person public Person clone () { return new Person(this); this used to refer to current object Copy constructor called on this Similar clone() methods definable for Student, Faculty New deepcopy() method: public static Person[] deepcopy (Person[] a) { Person[] r = new Person[a.length]; for (int i=0; i < a.length; i++) r[i] = a[i].clone(); return r; 12

equals() and clone(): A Summary When class inheritance, you may not know the actual classes of objects that you are manipulating. This complicates your job as a programmer. Set up your method parameters to be of the most general type that is applicable to your method (e.g. Object or Person rather than Student or Faculty). Whenever dealing with references to objects in the class hierarchy, use method overriding to produce the proper behavior. (E.g. using clone() rather than a copy constructor). 13

Inheritance vs. Composition Inheritance: a way to build new classes out of old ones Objects in subclass inherit data, methods from superclass Object in a subclass is-a (n) object in superclass Composition: another way to build new classes out of old Class definitions may include instance variables involving objects from other classes Object in a new class has-a (n) object in the original class 14

Example: Shapes public abstract class Shape { private int color; // Abstract class // Color of shape public class Circle extends Shape { // Concrete class private double radius; // Radius of circle private Point center; // Center of circle public class Rectangle extends Shape { // Concrete class private Point upperleft; // Upper left corner private Point lowerright; // Lower right corner Each Circle, Rectangle is-a Shape (inheritance) Each Circle has-a Point (center) (composition) Each Rectangle has-a two Points (upperleft, lowerright) 15

When To Use Inheritance, Composition? Ask is-a / has-a question Answer = is-a : inheritance Answer = has-a : composition 16