Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,

Slides:



Advertisements
Similar presentations
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Example - The.
Advertisements

Java Coding OOP David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Towards Event-driven programming &
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Everyday Algorithms David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. lightning introduction to.
Introduction to UML David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. …Unified Modeling Language.
Road Map Introduction to object oriented programming. Classes
Java Coding 6 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Collections.
Java Coding 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Decisions, decisions…!
Java Coding 3 David Davenport Computer Eng. Dept.,
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
Review: OOP & Arrays David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. …from CS101.
Java Coding David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey.
Java Coding 4 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Method madness.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!
Java Coding 5 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Classes CS 21a: Introduction to Computing I First Semester,
Technical Module : Pointers #1 2000/01Scientific Computing in OOCourse code 3C59 Technical Module : Pointers In this module we will cover Pointers to primitives.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Computational Algorithms David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. lightning introduction.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Java Coding 6 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Collections.
Java Coding OOP_3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Some important Java interfaces +
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Module 7: Constructors #1 2000/2001Scientific Computing in OOCourse code 3C59 Module 7: Constructors and Destructors: In this module we will cover: Constructors.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Java Coding 6 David Davenport Computer Eng. Dept.,
Topic: Classes and Objects
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
Java Coding – part 2 David Davenport Computer Eng. Dept.,
© Craig Zilles (adapted from slides by Howard Huang)
Java Coding 3 – part2 David Davenport Computer Eng. Dept.,
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
Java Coding 8 David Davenport Computer Eng. Dept.,
Java Review: Reference Types
The dirty secrets of objects
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
CS2102: Lecture on Abstract Classes and Inheritance
OOP Paradigms There are four main aspects of Object-Orientated Programming Inheritance Polymorphism Abstraction Encapsulation We’ve seen Encapsulation.
Java Coding 4 David Davenport Computer Eng. Dept.,
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Java Coding 6-extra David Davenport Computer Eng. Dept.,
Java Coding 6 – part2 David Davenport Computer Eng. Dept.,
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
Object Comparisons and Arrays
Java Coding 8 David Davenport Computer Eng. Dept.,
Java Coding 4 (part2) David Davenport Computer Eng. Dept.,
Classes CS 21a: Introduction to Computing I
Review of Previous Lesson
Classes, Objects and Methods
Java Coding 6_part3 David Davenport Computer Eng. Dept.,
References Revisted (Ch 5)
CMPE212 – Reminders Assignment 2 due next Friday.
slides created by Ethan Apter
© Craig Zilles (adapted from slides by Howard Huang)
Classes and Objects Object Creation
Java Coding 6 David Davenport Computer Eng. Dept.,
Java Coding 6 David Davenport Computer Eng. Dept.,
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Java Coding 5 – Part 2 David Davenport Computer Eng. Dept., To object or to reference… David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. email: david@bilkent.edu.tr Revised: 11/12/2018 ~ removed static vs. instance stuff from end and put in separate file! (still need to tidy some of the animations etc. for null / garbage collection, etc.) previous: 30/11/2017 ~ some more tweaks, garbage & null separated, ~~more in progress! 28/11/2017 ~ more tweaks! Object vs. reference… 29/11/2016 ~ minor tweaks! 25/11/2012, 7/12/2010

IMPORTANT… Students… Instructors… This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an email saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.

Object vs. Reference In the “real” world …so too in Java! Derya David CS101 instructor In real world we distinguish between an object itself & references to it (ways of referring to it), of which there may be many. David & Derya are two different individuals. David & CS101 instructor are not. Only one David (thank goodness?), but if cloned then would want to say the copy is a different individual (object) having identical properties. May think cloning is somewhat irrelevant, but far from it. In today’s world, “clones” are everywhere! Not yet in the form of people, but of (manufactured) objects! e.g. bottles of water, pens, cellphones, etc., etc. Each is an individual object, but one that shares all relevant properties when created. Java must (& does) match our “real world” intuitions. But need to change the mental model of memory we have been using (for primitive types.) Demonstrate how putting david’s data on paper in location “david”, and then the same data on a paper in another location “cs101Instructor” fails to conform to our intuitions (about how reality functions) during updates (e.g. to age) So, change mental model of memory to accommodate… now rather than putting paper into box (memory location) data is written (on paper) on a balloon that floats in mid-air & is attached to the box with a piece of string the same (paper) balloon can be held by strings coming from several boxes. Derya’s dad David2

cs101Instructor {Person} Object vs. Reference In the Java world…? david 23 david 22 david 22 derya 18 derya 19 david {Person} cs101Instructor {Person} derya {Person} Note: slide shows direct access to properties, which is BAD but, same applies when using methods! So, our abstract picture in Java now looks like this. This distinction between object & reference has two important implications: There are two notions of what “same” means and there are two notions of what “copy” means We will look at each of these in turn…. david.age++; derya.age++; Sys…( david.age ); Sys…( cs101Instructor.age ); oops!

cs101Instructor {Person} Object vs. Reference In the Java world need to revise our mental model! David Derya david 22 david 23 derya 19 derya 18 david {Person} derya {Person} Revised mental model… - info still on paper, - but now paper stuck to balloon, - and connected to a memory location/box by a piece of string! + restrictions: balloon can be attached by any number of strings but each box can hold only one piece of string! (note box may hold no string at all). So, our abstract picture in Java now looks like this. This distinction between object & reference has two important implications: There are two notions of what “same” means and there are two notions of what “copy” means We will look at each of these in turn…. cs101Instructor {Person} deryasDad {Person} David’s clone david2 {Person} david 22

Two Implications Separating object & reference has for Equality & for Copying

For Equality ~same or different? (1) Comparing objects myQCd {CD} Title B.R. Artist Queen Date 1976 Length 3:50 myCd {CD} Title Best of Artist Genesis Date 1983 Length 2:40 yourCd {CD} if ( myCd == yourCd) System.out.println( “Same”); else System.out.println( “Different”); Both these report different! Doesn’t exactly correspond to our intuitions. Sure they are different objects, but in another sense they are the same, they are copies of the same CD. “==“ is comparing references, not the object properties. “==“ says whether the references refer to the same individual object or to two distinct objects. So, only “myCd == myQCd” would give true. Title B.R. Artist Queen Date 1976 Length 3:50 yourQCd {CD} if ( myCd == yourQCd) System.out.println( “Same”); else System.out.println( “Different”);

For Equality ~same or different? (2) Define an “equals” method myQCd {CD} Title B.R. Artist Queen Date 1976 Length 3:50 myCd {CD} Title Best of Artist Genesis Date 1983 Length 2:40 yourCd {CD} if ( myCd.equals( yourCd) ) System.out.println( “Same”); else System.out.println( “Different”); Can write an equals method in CD class that compares CD’s by content, not reference. These should report different & same in accord with our intuitions. And, of course, “myCd.equals( myCd)” would give true! Note: for reasons we will come to later, the method signature should be “boolean equals( Object o)” rather than “boolean equals( CD aCd)” so need to check class is correct too, i.e. comparing same sorts of objects! Write such a method. Note: you could name the method anything you want, “equals” is the convention Java uses… so follow it! Title B.R. Artist Queen Date 1976 Length 3:50 yourQCd {CD} if ( myCd.equals( yourQCd) ) System.out.println( “Same”); else System.out.println( “Different”);

For Copying in primitive vs. Object types… Different Same! int i, j; j = i; i++; Sys…( i + “,” + j ); Person me, x; me = new Person( …); x = me; me.setComments( “nice!”); Sys… ( me.getComments() + “ “ + x.getComments(), ); Demonstrating that copying has different semantics for primitive and object type data. You should be able to see the parallel in the code segments. Note that “j = i;” and “x = me” look exactly the same! But the difference in kind (primitive vs. object) means they have different semantics. (obviously resulting from the object reference distinction) Different but j = i: looks-like x = me; Same!

For Copying ~copy vs. clone Title B.R. Artist Queen Date 1976 Length 3:50 Title B.R. Artist Queen Date 1976 Length 3:50 myCd {CD} yourQCd {CD} Copying merely copies the reference, making the copy refer to the same object. Clone involves creating an entirely new object and copying all the properties of the first into it. Write such a method. Note: This is crucial to parameter passing to and returning results from methods when using objects. Note: Java automatically provides a clone method for all objects, BUT be careful, it performs a “shallow” copy, which is fine for primitive types, but not necessarily for embedded objects (which end up shared by both the original and clone objects!) Note: doing clone() properly is a problem since it requires implementing clonable & handling exceptions!) Use copy constructors as an alternative. For example, yourQCd = new CD( myCd); favouriteCd {CD} Alternatively, use “copy constructor” yourQCd = new CD( myCd ); favouriteCd = myCd; yourQCd = myCd.clone(); Copies reference Copies object

Parameter passing Implications for The distinction btw object & reference results in two different notions of equality & two of copying! This has further implications for parameter passing to methods… Conventional distinction is between pass by value & pass by reference The former is “input only” (changes made to the formal param inside the method do not affect the corresponding actual param) The latter commonly allows both the reference & the object to be changed, however, Java passes the ref by value & allows only the objects properties to be changed! Thus object param’s in Java can be used for outputs from the method too! Parameter passing

Parameter Passing (1) Primitive types… a b i 5 6 5 6 main xyz main public int xyz( int i) { i++; return i; } 5 6 5 6 The copy-clone distinction has important consequences for parameter passing… Note: This, and the following examples, actually assume static methods, but this is irrelevant. Passing the actual to formal parameters entails “copying” them (this is a primitive type copy). Same for passing the result back… it involves “copying” the value (again a primitive type copy). NOTICE – changing formal parameter in method DOES NOT affect associated actual parameter variable. main int a, b; a = 5; b = xyz( a); Sys… ( a, b);

Parameter Passing (2) Object types… a b x main xyz main David 22 1000 “” public Person xyz( Person x) { x.setComments(“Nice); return x; } Nice a b main x xyz NOTICE – changing the properties of the object referred to by the formal parameter in the method DOES change the properties of the corresponding (actual parameter’s) object in the main method. In effect, technically speaking, objects are “passed by reference” in Java (while primitive types are “passed by value”). main Person a, b; a = new Person( “David” …); b = xyz( a); Sys… ( a.getComments() + b.getComments() );

Parameter Passing (3) Object types… a b x main xyz main David 22 1000 “” Derya 18 500 “” public Person xyz( Person x) { x = new Person( “Derya” …); x.setComments(“Nice); return x; } Nice a b main x xyz NOTICE – changing the reference of the formal parameter in the method DOES NOT change the corresponding actual parameter’s reference in the main method. main Person a, b; a = new Person( “David” …); b = xyz( a); Sys… ( a.getComments() + b.getComments() );

Special methods, garbage collection & null references Extra Bits…

All Objects… automatically have BUT boolean equals( Object) Object clone() String toString() int hashCode() BUT they may not do what you would like/expect, so implement yourself! Code using these methods will compile & run even if your class does not define them! Note: toString automatically called when you ask Java to print an Object. Normally it won’t print anything very pretty, so you write it to return a nice neat version of your objects properties, ready to be printed. equals() defaults to “==“ clone() defaults to “shallow copy” toString() defaults to “classname@hashCodeInHexadecimal” Note: see documentation for Object class for real details… in general, hashCode’s must be “equal for equal objects” hence changing “equals” really requires implementing “hashCode” hashCode - ignore for now - except to note that + technically changing equals requires changing hasCode + toString is ClassName + ‘@’ + hashCodeInHexaDecimal

Lost objects & null Java collects its garbage! aCd = null; Title B.R. Artist Queen Date 1976 Length 3:50 Title Best of Artist Genesis Date 1983 Length 2:40 yourCd {CD} What happens when “myCd = yourCd;” is executed? Variable only refers to one object at a time. So my Queen CD is lost… the string is cut and the balloon floats off into the atmosphere… Objects having no references to them cannot be used! They are effectively garbage (rubbish/trash to be “disposed” of) Java automatically collects such garbage allowing the space to be reused/recycled for other objects (thus ensuring that “memory leaks” do not clog up and eventually stop the system). “null” is a special value that can only be applied to references. Can compare references to null e.g. if ( aCd == null) or if ( myCd != null) Cannot compare references using <, >, <=, >= (or add, subtract or multiply them!) Note: Attempting to access the properties or methods of an object that doesn’t exist because the reference is null, results in a “nullPointerException”. It should be nullReferenceException or some such. The word pointer is the old terminology for reference! myCd {CD} aCd {CD} aCd = null; myCd = yourCd;

Consider splitting here..? i.e. make static vs instance as part3