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 &
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Introduction to UML David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. …Unified Modeling Language.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
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…!
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Java Coding 3 David Davenport Computer Eng. Dept.,
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!
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Java Coding 5 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CSSE501 Object-Oriented Development. Chapter 12: Implications of Substitution  In this chapter we will investigate some of the implications of the principle.
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.
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 +
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
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.
Today Encapsulation. Build a fully encapsulated Halloween class, going from Halloween1 to Halloween6 (eventually!): –The final version will have overloaded.
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.,
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Java Coding 3 – part2 David Davenport Computer Eng. Dept.,
Java Review: Reference Types
The dirty secrets of objects
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.
Object Oriented Programming COP3330 / CGS5409
Java Coding 4 David Davenport Computer Eng. Dept.,
Java Programming Language
Phil Tayco Slide version 1.0 Created Oct 9, 2017
slides created by Ethan Apter
Arrays in Java What, why and how Copyright Curt Hill.
Java Coding 6-extra David Davenport Computer Eng. Dept.,
slides created by Ethan Apter
Today’s topics UML Diagramming review of terms
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,
Java Coding 4 (part2) David Davenport Computer Eng. Dept.,
Review of Previous Lesson
Review of Previous Lesson
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
Java Coding 6_part3 David Davenport Computer Eng. Dept.,
slides created by Ethan Apter and Marty Stepp
References Revisted (Ch 5)
CMPE212 – Reminders Assignment 2 due next Friday.
Visibilities and Static-ness
Classes and Objects Object Creation
Java Coding 6 David Davenport Computer Eng. Dept.,
C++ Object Oriented 1.
Java Coding 6 David Davenport Computer Eng. Dept.,
SPL – PS3 C++ Classes.
CMSC 202 Constructors Version 9/10.
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
Presentation transcript:

Java Coding 5 – Part 2 David Davenport Computer Eng. Dept., To object or not… David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. email: david@bilkent.edu.tr Revised: 28/11/2017 ~ more tweaks! Object vs. reference… previous: 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} 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 (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! & hashCode, but perhaps ignore for now! 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”

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;

Static vs. Instance

Static vs. instance Variables “count” as an instance variable -- each instance (object) has count variable name age salary comments Person c.count++; a.count = 3; count instance Could (1) have int count variable outside class-but difficult to maintain, (2) associate with class, but can’t be instance variable-why not? (3) make static variable in class… only one copy in class, not instances. Here, count is initialised to zero when declared(!), then incremented in constructor. Each instance of the class, i.e. each individual object, has its own values for each instance variable. But there is only ever one copy of a static variable (also called a class variable.) Static data accessible via classname.variablename (and object.variablename) Instance data only accessible via object.variablename syntax. Static data can be accessed even if there are no instances of the class. Same goes for static methods, e.g. a getCount() method here or the main method! Note: static methods can only refer to static data (and data defined locally in method.) Why? Static data used for constant definitions (outside method but in class) –never changes so only need one copy! for singletons (classes which allow one and only one object to be created.) David 22 2000 “Quiet” Derya 18 500 “Nice” Gunes 21 1500 “Sunny” Ayse 25 1000 “Happy” 3 2 a b c d

Static vs. instance Variables “count” as a static variable -- only one count variable, associated with class name age salary comments Person also known as “class variables” static count 1 4 2 3 initialise count to zero, then increment it in constructor instance Could (1) have int count variable outside class-but difficult to maintain, (2) associate with class, but can’t be instance variable-why not? (3) make static variable in class… only one copy in class, not instances. Here, count is initialised to zero when declared(!), then incremented in constructor. Each instance of the class, i.e. each individual object, has its own values for each instance variable. But there is only ever one copy of a static variable (also called a class variable.) Static data accessible via classname.variablename (and object.variablename) Instance data only accessible via object.variablename syntax. Static data can be accessed even if there are no instances of the class. Same goes for static methods, e.g. a getCount() method here or the main method! Note: static methods can only refer to static data (and data defined locally in method.) Why? Static data used for constant definitions (outside method but in class) –never changes so only need one copy! for singletons (classes which allow one and only one object to be created.) David 22 2000 “Quiet” Derya 18 500 “Nice” Gunes 21 1500 “Sunny” Ayse 25 1000 “Happy” a b c d

Misc: Can combine, so static “nextID” gives next value to be assigned to instance variable “personID”. Constants often defined as static hence saving space public static final double PI = 3.142; public static final String COMPANY = “Bilkent University”;

Static vs. instance Methods Classes can have both static & instance methods. Static methods useful when accessing static variables public static int getCount() object state is not needed public static int getAge( day, month, year) Static methods cannot access instance variables or methods Instance methods can access static & instance, variables & methods Why are static methods not allowed to access instance variables (or instance methods!)

Singletons (design pattern) Problem: Ensure only a single instance of a class is created. (for database or network connections, etc.) Solution: Combine static variable, private constructor & static method! public class SingletonClass { private static SingletonClass singletonObj = new SingletonClass(); private SingletonClass() { } public static SingletonClass getInstance() { return singletonObj; Other uses include print spoolers… Note: can also do lazy creation of object by only creating it if property is null. A number of further considerations may apply in practice, e.g. need to override clone method, make synchronized if multiple threads, etc.

Can also mention “this” if not already done so… generally introduce as way to resolve parameter/property names in constructors. And don’t forget about the sorts of relationships between objects, i.e. is_a, has_a and uses. One day, introduce UML notations! Now… practice makes perfect (or at least helps you on the way!)