Classes Classes 2 / 35

Similar documents
Classes Classes 2 / 36

Classes. 1 Data Abstraction. 2 A Complex Number ADT

CS1004: Intro to CS in Java, Spring 2005

Chapter 4 Defining Classes I

Introduction to Object-Oriented Programming

Aggregation and Composition. [notes Chapter 4]

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

public Student(int theage, String thename, char thegrade) { age = theage; name = thename; grade = thegrade; } public int getage() { return age;}

Refresher: Interface Specifications. ADT Documentation. Set Represented as an Array. Representation Invariant, Abstraction Function

Representation Invariant, Abstraction Function

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Anatomy of a Class Encapsulation Anatomy of a Method

More About Objects and Methods

Chapter 4: Writing Classes

Lecture 2: Java & Javadoc

CS1004: Intro to CS in Java, Spring 2005

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

Java Fundamentals (II)

9/17/2018 Programming Data Structures. Encapsulation and Inheritance

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

PIC 20A The Basics of Java

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Review Questions II KEY

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

7. Arrays, More Java Looping

Arrays. Chapter 7 (Done right after 4 arrays and loops go together, especially for loops)

Recommended Group Brainstorm (NO computers during this time)

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

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

CS 2340 Objects and Design - Scala

Week 3 Classes and Objects

Introduction to Programming Using Java (98-388)

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Creating an Immutable Class. Based on slides by Prof. Burton Ma

CS1083 Week 2: Arrays, ArrayList

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Inf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics

CS 302 Week 9. Jim Williams

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

COP 3330 Final Exam Review

Defensive Programming Best Practices

Creating an object Instance variables

CMSC 132: Object-Oriented Programming II

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Programming for Engineers Pointers

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

Chapter 13: Arrays of Objects

CSCI 1301: Introduction to Computing and Programming Summer 2018 Lab 07 Classes and Methods

20 Subclassing and Mutation

Inf1-OOP. Arrays. Many Variables of the Same Type. Arrays Introduction to Arrays Arrays in Java Shuffling a Deck Multidimensional Arrays Summary/Admin

Principles of Object Oriented Programming. Lecture 4

For this section, we will implement a class with only non-static features, that represents a rectangle

Inf1-OOP. Arrays 1. Perdita Stevens, adapting earlier version by Ewan Klein. January 11, School of Informatics

CSCI 1301: Introduction to Computing and Programming Spring 2019 Lab 10 Classes and Methods

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

CS 251 Intermediate Programming Java Basics

Java and OOP. Part 2 Classes and objects

Introduction to Computing II (ITI 1121) Final Examination

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Classes, interfaces, & documentation. Review of basic building blocks

CSCE 156 Computer Science II

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Chapter 6 - Pointers

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

6.005 Elements of Software Construction Fall 2008

Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Lecture 7: Data Abstractions

Objects and Classes Continued. Engineering 1D04, Teaching Session 10

CS 231 Data Structures and Algorithms, Fall 2016

Introduction to Java Written by John Bell for CS 342, Spring 2018

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

The class Object. Lecture CS1122 Summer 2008

1/27/2014. OO design approach with examples. UML and project clarifications (2) Project clarifications 1. UML

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Domain-Driven Design Activity

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Relationship between Pointers and Arrays

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

INHERITANCE. Spring 2019

CSE 341, Autumn 2015, Ruby Introduction Summary

Chapter 5: Writing Classes and Enums

Review questions. Review questions, cont d. Class Definition. Methods. Class definition: methods. April 1,

ITI Introduction to Computing II

CS111: PROGRAMMING LANGUAGE II

JAVA MOCK TEST JAVA MOCK TEST II

Who we are: Lecture 1: Overview & Java. Why CS 62? Sample Problems. CS 62 Fall 2016 Kim Bruce & Peter Mawhorter

CS201 - Assignment 1, Part 2 Due: Wednesday February 19, at the beginning of class

CS201 - Assignment 3, Part 1 Due: Friday February 28, at the beginning of class

Transcription:

Classes 1 / 35

Classes Classes 2 / 35

Anatomy of a Class By the end of next lecture, you ll understand everything in this class definition. package edu. gatech. cs1331. card ; import java. util. Arrays ; public class Card { public static final String [] VALID_RANKS = {"2",..., " ace "; public static final String [] VALID_SUITS = {" diamonds ",... ; private String rank ; private String suit ; public Card ( String arank, String asuit ) { //... public String tostring () { return rank + " of " + suit ; private boolean isvalidrank ( String somerank ) {... 3 / 35

The Card Class Example In this lecture we ll use a running example stored in a Git repo. Go to https://github.com/cs1331/card, click on "Clone or download" and copy the clone URL. Then open your terminal and do this: cd cs1331 git clone https :// github. com / cs1331 / card. git cd card Note that if you ve uplaoded your public SSH key you may use an SSH clone URL. Now you re ready to follow along. Start by checking out v0.0 1 : git checkout v0.0 1 Semantic Versioning 4 / 35

A Card Class, v0.0 Consider how to represent a Card ADT: rank - the rank of a playing card, e.g., 2, jack, ace suit - the suit of a playing card, e.g., spades, diamonds public class Card { String rank ; String suit ; rank and suit are instance variables Every instance of Card has its own copy of instance variables. Let s "do something" with Card by adding a main method and bumping to v0.1. 5 / 35

Card v0.1 After git checkout v0.1 we have (we won t include the git commands in future slides): public class Card { String rank ; String suit ; public static void main ( String [] args ) { Card c = new Card (); System. out. println (c); Note that we can put a main method in any class. This is useful for exploratory testing, like we re doing here. The String representation isn t very appealing. (What does it print?) 6 / 35

Card v0.2 public class Card { String rank ; String suit ; public String tostring () { return rank + " of " + suit ; public static void main ( String [] args ) { Card swedishpop = new Card (); swedishpop. rank = " ace "; swedishpop. suit = " base "; Card handy = new Card (); handy. rank = " jack "; handy. suit = " all trades "; System. out. println ( swedishpop ); System. out. println ( handy ); Now we have a nice String representation, but we havve an "ace of base" card and a "jack of all trades", which aren t valid cards. 7 / 35

Encapsulation: Card, v1.0 Let s protect the instance variables by making them private: public class Card { private String rank ; private String suit ; public String tostring () { return rank + " of " + suit ; public static void main ( String [] args ) { Card c = new Card (); c. rank = " ace "; c. suit = " base "; System. out. println (c); Why does this still compile? main method in Card can see Card s private parts 8 / 35

A Dealer Class, v1.1 public class Dealer { public static void main ( String [] args ) { Card c = new Card (); c. rank = " ace "; c. suit = " base "; System. out. println (c); This won t compile (which is what we want). Why? 9 / 35

Mutators: Card, v1.2 public class Card { private String rank ; private String suit ; public void setrank ( String rank ) { rank = rank ; public void setsuit ( String suit ) { suit = suit ; Now client code can set the rank and suit of a card by calling setrank and setsuit. setx is the Java convention for a setter method for an instance variable named x. 10 / 35

Dealing Card, v1.2 Let s try out our new Card class. public class Dealer { public static void main ( String [] args ) { Card c = new Card (); c. setrank (" ace "); c. setsuit (" base "); System. out. println (c); Oops. Prints "null of null". Why? 11 / 35

Shadowing Variables The parameters in the setters "shadowed" the instance variables: public void setrank ( String rank ) { rank = rank ; public void setsuit ( String suit ) { suit = suit ; rank in setrank refers to the local rank variable, not the instance variable of the same name suit in setsuit refers to the local suit variable, not the instance variable of the same name 12 / 35

Dealing with this : Card, v1.2.1 public class Card { private String rank ; private String suit ; public void setrank ( String rank ) { this. rank = rank ; public void setsuit ( String suit ) { this. suit = suit ; Every instance of a class has a this reference which refers to the instance on which a method is being called. this.rank refers to the rank instance variable for the Card instance on which setrank is being called. this.rank is different from the local rank variable that is a parameter to the setrank method. 13 / 35

Dealing Card, v1.2.1 public class Dealer { public static void main ( String [] args ) { Card c = new Card (); c. setrank (" ace "); c. setsuit (" base "); System. out. println (c); Now we have encapsulation, but we can still create invalid Card s, e.g., "base" is not a valid suit. How to fix? 14 / 35

Class Invariants Class invariant: a condition that must hold for all instances of a class in order for instances of the class to be considered valid. Invariants for Card class: rank must be one of {"2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace" suit must be one of {"diamonds", "clubs", "hearts","spades" 15 / 35

Class Invariants: Card v1.3 rank invariant can be maintained by adding: public class Card { private final String [] VALID_RANKS = {"2", "3", "4", "5", "6", "7", "8", "9", "10", " jack ", " queen ", " king ", " ace "; public void setrank ( String rank ) { if (! isvalidrank ( rank )) { System. out. println ( rank + " is not a valid rank."); System. exit (0) ; this. rank = rank ; private boolean isvalidrank ( String somerank ) { return contains ( VALID_RANKS, somerank ); private boolean contains ( String [] array, String item ) { for ( String element : array ) { if ( element. equals ( item )) { return true ; return false ; //... 16 / 35

Class Invariants Ensure Consistent Objects Now we can t write code that instantiates an invalid Card object: public class Dealer { public static void main ( String [] args ) { Card c = new Card (); c. setrank (" ace "); c. setsuit (" base "); System. out. println (c); yields: $ java Dealer base is not a valid suit. 17 / 35

Dealer v1.3.1 Version 1.3.1 fixes the invalid suit: public class Dealer { public static void main ( String [] args ) { Card c = new Card (); c. setrank (" ace "); c. setsuit (" spades "); System. out. println (c); 18 / 35

Initializing Instances (v1.4) Card now ensures that we don t create card objects with invalid ranks or suits. But consider this slight modification to Dealer in v1.4: public class Dealer5 { public static void main ( String [] args ) { Card c = new Card (); System. out. println (c); // Printing a new Card instance c. setrank (" ace "); c. setsuit (" base "); System. out. println (c); What if we printed our Card instance, c, before we called the setters? 19 / 35

Object Initialization Two ways to initialize the instance variables of an object: Declaration point initialization: public class Card { private String rank = "2"; //... Constructors public class Card { public Card () { rank = "2"; //... A constructor is what s being called when you invoke operator new. 20 / 35

Initializing Objects Since we didn t write our own constructor, Java provided a default no-arg constructor default no-arg ctor sets instance variables (that don t have their own declaration-point intializations) to their default values. That s why a Card object s instance variables are null (" null of null ") after they re instantiated. We have to call the setters on a Card instance before we have a valid object. 21 / 35

Innitialization Style In general, it s poor style to require multi-step initialization. After new Card() is called, instance variables have useless defaults. Client programmer must remember to call setter methods. Often there can be order dependencies that we don t want to burden client programmers with. The way to fix this is by writing our own constructor. 22 / 35

A Constructor for Card, v2.0 If we write a constructor, Java won t provide a default no-arg constructor. public class Card { //... public Card ( String rank, String suit ) { setrank ( rank ); setsuit ( suit ); //... If we want a no-arg constructor in addition to other constructors, we must write it explicitly. 23 / 35

Dealer v2.0 Now this won t even compile: public class Dealer { public static void main ( String [] args ) { Card c = new Card (); //... $ javac Dealer. java Dealer. java :4: error : constructor Card in class Card cannot be applied to given types ; Card c = new Card (); ^ required : String, String found : no arguments reason : actual and formal argument lists differ in length 1 error 24 / 35

Using the Card v2.0.1 Constructor Now we have a safer, more consistent way to initialize objects: public class Dealer { public static void main ( String [] args ) { Card c = new Card (" queen ", " hearts "); System. out. println (c); 25 / 35

Progress Check Let s review our progress with our Card class design: We have a nice string representation of Card objects. We have encapsulated the rank and suit in private instance variables with mutator methods to set their values. We validate the rank and suit in the mutator methods so we can t set invalid ranks and suits in Card objects. Card has a constructor, which ensures that instance variables are initialized when an instance of Card is created. 26 / 35

Valid Ranks and Suits Recall the declarations and definitions of our VALID_RANKS and VALID_SUITS : public final String [] VALID_RANKS = {"2", "3", "4", "5", "6", "7", "8", "9", "10", " jack ", " queen ", " king ", " ace "; public final String [] VALID_SUITS = {" diamonds ", " clubs ", " hearts "," spades "; Do we need a separate instance of VALID_RANKS and VALID_SUITS for each instance of our Card class? 27 / 35

Static Members, Card v2.1 static members are shared with all instances of a class: public static final String [] VALID_RANKS = {"2", "3", "4", "5", "6", "7", "8", "9", "10", " jack ", " queen ", " king ", " ace "; public static final String [] VALID_SUITS = {" diamonds ", " clubs ", " hearts "," spades "; Given the declarations above: Each instance shares a single copy of VALID_RANKS and a single copy of VALID_SUITS Since they re final, we can safely make them public so clients of our Card class can use them 28 / 35

Stateful Card Objects? Card v2.1 is pretty good, but we can write code like this: public class Dealer { public static void main ( String [] args ) { Card c = new Card (" queen ", " hearts "); System. out. println (c); c. setrank (" jack "); // modifying c System. out. println (c); Does this make sense? Should Card objects be mutable? 29 / 35

Immutable Objects Card objects don t change. We can model this behavior by removing the setters and putting the initialization code in the constructor (or making the setters private and calling them from the constructor): public Card ( String arank, String asuit ) { // constructor if (! isvalidrank ( rank )) { System. out. println ( arank + " is not a valid rank."); System. exit (0) ; rank = arank ; if (! isvalidsuit ( asuit )) { System. out. println ( asuit + " is not a valid suit."); System. exit (0) ; suit = asuit ; Note the use of another idiom for disambiguating constructor paramters from instance variables (as opposed to using this ). 30 / 35

A Few Final Bits of Polish Take a look at the final evolution of our Card class. git checkout master It contains a few more enhancements: It has an equals() method for comparing cards of equal value. We ll learn the role of the equals method today and learn how to write one in a couple of weeks. It uses enum s for rank and suit. 31 / 35

Enums public enum Rank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE public enum Rank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE Now we get static type checking for Rank and Suit no need for run-time validity checks. public class Card {... private Rank rank ; private Suit suit ; public Card ( Rank arank, Suit asuit ) { rank = arank ; suit = asuit ; 32 / 35

Equality For reference types: == means identity equality (aliasing testing). equals(object) tests value equality, as defined by the class. For primitive types == means value equality and is the only equality test. Here s the final Card class, with a definition of value equality for Card instances: public class Card { private Rank rank ; private Suit suit ; public Card ( Rank arank, Suit asuit ) { rank = arank ; suit = asuit ; public String tostring () { return rank + " of " + suit ; public boolean equals ( Object other ) { if ( null == other ) { return false ; if ( this == other ) { return true ; if (!( other instanceof Card )) { return false ; Card that = ( Card ) other ; return this. rank. equals ( that. rank ) && this. suit. equals ( that. suit ); 33 / 35

Equality Tests Given our finished Card class with a properly implemented equals(object) method, this code: Card c1 = new Card ( Rank.ACE, Suit. SPADES ); Card c2 = new Card ( Rank.ACE, Suit. SPADES ); Card c3 = c1; System. out. println (" c1 == c2 returns " + ( c1 == c2)); System. out. println (" c1. equals ( c2) returns " + c1. equals ( c2)); System. out. println (" c1 == c3 returns " + ( c1 == c3)); System. out. println (" c1. equals ( c3) returns " + c1. equals ( c3)); produces this output: c1 == c2 returns false c1. equals ( c2) returns true c1 == c3 returns true c1. equals ( c3) returns true By the way, what if we left off the parentheses around c1 == c2 in System.out.println("c1 == c2 returns " + (c1 == c2))? 34 / 35

Exercise: Treating People as Objects Using the encapsulation techniques we just learned, write a class named Person with a name field of type String and an age field of type int. Write a suitable tostring method for your Person class. Add a main method that: Creates an array of Person objects Iterates through the array and prints each Person object who s age is greater than 21 35 / 35