A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.

Slides:



Advertisements
Similar presentations
Computer Science 209 The Singleton Pattern. Random Numbers System.out.println((int)(Math.random() * 6) + 1); Math.random() uses a single generator that.
Advertisements

CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
New features in JDK 1.5 Can these new and complex features simplify Java development?
Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view class.
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Identity and Equality Based on material by Michael Ernst, University of Washington.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Objects, Variables & Methods Java encapsulates data and action modules that access the data in one container, called an object. Object members that.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
CSS446 Spring 2014 Nan Wang.  To learn how to choose appropriate classes for a given problem  To understand the concept of cohesion  To minimize dependencies.
© Amir Kirsh Object Oriented Programming with Java Written by Amir Kirsh.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
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.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
Composition (Part 2) 1. Class Invariants  class invariant  some property of the state of the object that is established by a constructor and maintained.
A Semantic Error in Google last weekend! Someone in Google typed an extra ‘/’ character into their URL List Link to CNN video report posted on Collab.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
Not overriding equals  what happens if you do not override equals for a value type class?  all of the Java collections will fail in confusing ways 1.
Utilities (Part 2) Implementing static features 1.
1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.
Goals for Today 1  Multiton  maps  static factory methods.
Mixing Static and Non-static
Inheritance (Part 4) Polymorphism and Abstract Classes 1.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Inheritance (Part 2) Notes Chapter KomondorBloodHound PureBreedMix Dog Object Dog extends Object PureBreed extends Dog Komondor extends PureBreed.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Puzzle 1  what does the following program print? public class Puzzle01 { public static void main(String[] args) { System.out.print("C" + "S" + "E"); System.out.println('1'
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
Topic 7 Interfaces I once attended a Java user group meeting where James Gosling (one of Java's creators) was the featured speaker. During the memorable.
Composition  recall that an object of type X that is composed of an object of type Y means  X has-a Y object and  X owns the Y object  in other words.
Composition 1.  recall that an object of type X that is composed of an object of type Y means  X has-a Y object and  X owns the Y object  in other.
Mixing Static and Non-static Singleton 1. Singleton Pattern 2  “There can be only one.”  Connor MacLeod, Highlander.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 10 Thinking.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Chapter 10 Thinking in Objects
Aggregation and Composition
Chapter 10 Thinking in Objects
Chapter 10 Thinking in Objects
The hashCode method.
Computer Science 209 The Singleton Pattern.
CS 302 Week 11 Jim Williams, PhD.
Non-static classes.
CS 302 Week 10 Jim Williams.
Chapter 9 Thinking in Objects
CSE 1030: Implementing Mixing static and non-static features
Implementing Non-Static Features
Chapter 9 Thinking in Objects
Basics of OOP A class is the blueprint of an object.
Object Oriented Programming Review
First Semester Review.
CS 240 – Advanced Programming Concepts
Presentation transcript:

A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR); private Elvis() { this.beltSize = CURRENT_YEAR – 1930; } public int getBeltSize() { return this.beltSize; } public static void main(String[] args) { System.out.println("Elvis has a belt size of " + INSTANCE.getBeltSize()); } from Java Puzzlers by Joshua Bloch and Neal Gafter

A Singleton Puzzle: Solution  Elvis has a belt size of is printed  to solve the puzzle you need to know how Java initializes classes (JLS 12.4)  the call to main() triggers initialization of the Elvis class (because main() belongs to the class Elvis)  the static attributes INSTANCE and CURRENT_YEAR are first given default values ( null and 0, respectively)  then the attributes are initialized in order of appearance 2

1. public static final Elvis INSTANCE = new Elvis(); 2. this.beltSize = CURRENT_YEAR – 1930; 3. private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR); the problem occurs because initializing INSTANCE requires a valid CURRENT_YEAR solution: move CURRENT_YEAR before INSTANCE 3 CURRENT_YEAR == 0 at this point

Aggregation and Composition [notes Chapter 4] 4

Aggregation and Composition  the terms aggregation and composition are used to describe a relationship between objects  both terms describe the has-a relationship  the university has-a collection of departments  each department has-a collection of professors  composition implies ownership  if the university disappears then all of its departments disappear  a university is a composition of departments  aggregation does not imply ownership  if a department disappears then the professors do not disappear  a department is an aggregation of professors 5

Aggregation  suppose a Person has a name and a date of birth public class Person { private String name; private Date birthDate; public Person(String name, Date birthDate) { this.name = name; this.birthDate = birthDate; } public Date getBirthDate() { return birthDate; } 6

 the Person example uses aggregation  notice that the constructor does not make a copy of the name and birth date objects passed to it  the name and birth date objects are shared with the client  both the client and the Person instance are holding references to the same name and birth date 7 // client code somewhere String s = "Billy Bob"; Date d = new Date(91, 2, 26); // March 26, 1991 Person p = new Person(s, d);

8 64 client s250 d350 p String object Date object Person object name250 birthDate350

 what happens when the client modifies the Date instance?  prints Fri Nov 03 00:00:00 EST // client code somewhere String s = "Billy Bob"; Date d = new Date(90, 2, 26); // March 26, 1990 Person p = new Person(s, d); d.setYear(95); // November 3, 1995 d.setMonth(10); d.setDate(3); System.out.println( p.getBirthDate() );

 because the Date instance is shared by the client and the Person instance:  the client can modify the date using d and the Person instance p sees a modified birthDate  the Person instance p can modify the date using birthDate and the client sees a modified date d  note that even though the String instance is shared by the client and the Person instance p, neither the client nor p can modify the String  immutable objects make great building blocks for other objects  they can be shared freely without worrying about their state 10

UML Class Diagram for Aggregation 11 PersonStringDate 11 number of Date objects each Person has number of String objects each Person has open diamonds indicate aggregation

Aggregation Example  suppose we want to implement a class to represent standard playing cards  a card has-a suit (club, diamond, heart, spade)  we will represent the suit with a String  a card has-a rank (2, 3, 4, …, jack, queen, king, ace)  we will represent the rank with a String  cards have a natural ordering (by rank; we will assume aces are the highest rank)  impose a class-invariant  the suit and rank are always valid for a constructed card 12 CardString 2

CardUtil  we will find it useful to create a utility class that defines the legal ranks and suits of cards package playingcard; import java.util.HashMap; import java.util.ArrayList; final class CardUtil { static final HashMap RANKS = createRanks(); static final ArrayList SUITS = createSuits(); 13 no access modifier means that CardUtil is "package private"; only classes inside the package playingcard can see CardUtil

CardUtil static HashMap createRanks() { HashMap r = new HashMap (); r.put("two", 2); r.put("three", 3); r.put("four", 4); // and so on... r.put("queen", 12); r.put("king", 13); r.put("ace", 14); return r; } 14

CardUtil static ArrayList createSuits() { ArrayList s = new ArrayList (); s.add("club"); s.add("diamond"); s.add("heart"); s.add("spade"); return s; } 15

Card package playingcard; public class Card implements Comparable { private final String rank; private final String suit; public Card(String rank, String suit) { checkRank(rank); checkSuit(suit); this.rank = rank; this.suit = suit; } 16 Remember the class invariant: the rank and suit must always be valid for a constructed card; we have to validate the rank and suit arguments.

Card private void checkRank(String rank) { if(CardUtil.RANKS.get(rank) == null) { throw new IllegalArgumentException(rank + " is not a valid Card rank."); } 17 Remember that CardUtil.RANKS is a map where the keys are Strings like "two", "ace", and "seven". CardUtil.RANKS holds all of the valid ranks as keys. If the key given by the String rank is not in the map then it must be an invalid rank.

Card private void checkSuit(String suit) { if(!CardUtil.SUITS.contains(suit)) { throw new IllegalArgumentException(suit + " is not a valid Card suit."); } 18 Remember that CardUtil.SUITS is a list holding all of the valid suits. If the suit given by the String suit is not in CardUtil.SUITS then it must be an invalid suit.

Card public String getRank() { return this.rank; } public String getSuit() { return this.suit; } 19

public boolean equals(Object obj) { boolean eq = false; if(this == obj) { eq = true; } else if(obj != null && this.getClass() == obj.getClass()) { Card other = (Card) obj; eq = this.getRank().equals(other.getRank()) && this.getSuit().equals(other.getSuit()); } return eq; } 20 Remember the pattern for implementing equals is always the same: 1.check if this and obj are the same object 2.check if obj is not null AND 3.this and obj are instances of the same class 4. check if the corresponding attributes are equals Remember to watch out for the case where the attributes can be null; this complicates step 4.

public int hashCode() { return this.getRank().hashCode() + this.getSuit().hashCode(); public String toString() { StringBuffer result = new StringBuffer(); result.append(this.getRank()); result.append(" of "); result.append(this.getSuit()); result.append("s"); return result.toString(); } 21 Remember that because we overrode equals we need to override hashCode.

public int compareTo(Card other) { String myRank = this.getRank(); String otherRank = other.getRank(); Integer myValue = CardUtil.RANKS.get(myRank); Integer otherValue = CardUtil.RANKS.get(otherRank); return myValue.intValue() - otherValue.intValue(); } 22 Remember that if we choose to implement Comparable, we have to implement compareTo. compareTo must return: 1.a negative intif the value of this is less than the value of other 2.zero if the value of this is the same as the value of other 3.a positive intif the value of this is greater than the value of other