Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality

Similar documents
Designing data types. Fundamentals of Computer Science I

Procedural programming. [verb-oriented] Tell the computer to do this. (Spring 2012)

More on methods and variables. Fundamentals of Computer Science Keith Vertanen

Inf1-OOP. Encapsulation and Collections. Perdita Stevens, adapting earlier version by Ewan Klein. March 2, School of Informatics

Inf1-OOP. Encapsulation. Object Oriented Programming. Encapsulation Accessing Data Immutability. Encapsulation and Collections.

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

Admin. CS 112 Introduction to Programming. Exercise: Gene Finding. Language Organizing Structure. Gene Finding. Foundational Programming Concepts

CLASSES AND OBJECTS. Fundamentals of Computer Science I

CLASSES AND OBJECTS. Fundamentals of Computer Science I

"Hello" " This " + "is String " + "concatenation"

More on variables and methods

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

Classes and objects. Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates

Lecture 16: Encapsulation and ADTs

Chapter 4 Defining Classes I

CS 231 Data Structures and Algorithms, Fall 2016

Software engineering as managing change. Inf1-OP. Data representation. How can we make change easier and cheaper?

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Inf1-OP. Classes and Objects. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. November 23, School of Informatics

STUDENT LESSON A10 The String Class

Java Object Oriented Design. CSC207 Fall 2014

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

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

CSI33 Data Structures

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

More non-primitive types Lesson 06

Welcome to the Using Objects lab!

Utilities (Part 2) Implementing static features

IS502052: Enterprise Systems Development Concepts Lab 1: Java Review

Object-Oriented Programming Concepts

Object Oriented Programming

appreciate the difference between a char and a string understand and use the String class methods

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

CSE1710. Big Picture. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

Chapter 6 Introduction to Defining Classes

Strings! Today! CSE String Methods!

String is a Class; Quoted Text is an Object

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Defining Classes and Methods

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Simple Component Writer's Guide

Introduction to Programming Using Java (98-388)

Chapter 1 Introduction to java

Lesson:9 Working with Array and String


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

JAVA: A Primer. By: Amrita Rajagopal

Lecture 4. Strings, Wrappers, & Containers

EECS168 Exam 3 Review

Eng. Mohammed Abdualal

York University Fall 2001 / Test #1 Department of Computer Science

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

Classes Classes 2 / 36

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

CS1004: Intro to CS in Java, Spring 2005

Introduction to Classes and Objects. David Greenstein Monta Vista High School

Handout 7. Defining Classes part 1. Instance variables and instance methods.

JAVA MOCK TEST JAVA MOCK TEST II

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.

9 Working with the Java Class Library

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

A Founda4on for Programming

Lab 14 & 15: String Handling

Class Foo. instance variables. instance methods. Class FooTester. main {

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Using Java Classes Fall 2018 Margaret Reid-Miller

Assignment 1 due Monday at 11:59pm

An Introduction to C++

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

Week 7 - More Java! this stands for the calling object:

Topics. Class Basics and Benefits Creating Objects.NET Architecture and Base Class Libraries 3-2

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

BM214E Object Oriented Programming Lecture 8

Inf1-OP. Creating Classes. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

A variable is a name for a location in memory A variable must be declared

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

We now start exploring some key elements of the Java programming language and ways of performing I/O

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

CSC 222: Object-Oriented Programming. Spring 2017

Static methods. Not actually a valid Java static method. Fundamentals of Computer Science Keith Vertanen

Lecture 8: The String Class and Boolean Zen

Designing and Implementing Classes Topic 6

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

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

CS112 Lecture: Characters and Strings

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

Operations. I Forgot 9/4/2016 COMPUTER SCIENCE DEPARTMENT PICNIC. If you forgot your IClicker, or your batteries fail during the exam

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Mutable and Immutable Objects

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

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

AP Computer Science A

Creating Strings. String Length

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

Transcription:

Designing data types Overview Object Oriented Programming (OOP) Data encapsulation Important consideration when designing a class Access modifiers Immutability, preventing change to a variable Checking for equality Not always has simple as you might think! floating-point variables reference variables String variables Fundamentals of Computer Science Keith Vertanen Copyright 2013 2 Object Oriented Programming Procedural programming [verb-oriented] Tell the computer to do this Tell the computer to do that OOP philosophy Software simulation of real world We know (approximately) how the real world works Design software to model the real world Objected oriented programming (OOP) [noun-oriented] Programming paradigm based on data types Identify: objects that are part of problem domain or solution Objects are distinguishable from each other (references) State: objects know things (instance variables) Behavior: objects do things (methods) 3 Alan Kay Alan Kay [Xerox PARC 1970s] Invented Smalltalk programming language Conceived portable computer Ideas led to: laptop, modern GUI, OOP The computer revolution hasn't started yet. The best way to predict the future is to invent it. If you don't fail at least 90 per cent of the time, you're not aiming high enough. Alan Kay Alan Kay 2003 Turing Award Dynabook: A Personal Computer for Children of All Ages, 1968. 4

Data encapsulation Data type "Set of values and operations on those values" e.g. int, String, Charge, Picture, Enemy, Player Encapsulated data type Hide internal representation of data type. Separate implementation from design specification Class provides data representation & code for operations Client uses data type as black box API specifies contract between client and class Bottom line: You don't need to know how a data type is implemented in order to use it 5 Client Client needs to know how to use API Intuition API - volume - change channel - adjust picture - decode NTSC signal Implementation and client need to agree on API ahead of time. Implementation - cathode ray tube - electron gun - Sony Wega 36XBR250-241 pounds Implementation needs to know what API to implement 6 Intuition Time Bombs Internal representation changes [Y2K] Two digit years: Jan 1, 2000 [Y2038] 32-bit seconds since 1970: Jan 19, 2038 Client API - volume - change channel - adjust picture - decode NTSC signal Implementation - gas plasma monitor - Samsung FPT-6374 - wall mountable - 4 inches deep Client needs to know how to use API Can substitute better implementation without changing the client. Implementation needs to know what API to implement 7 Lesson http://xkcd.com/607/ By exposing data representation to client, may need to sift through millions of lines of code to update 8

Access modifiers Data encapsulation example Access modifier Person class All instance variables and methods have one public - everybody can see/use private - only class can see/use protected - only class and subclasses (stay tuned) default - everybody in package, what you get if you don't specify an access modifier Normally: Instance variables are private Methods the world needs are public Helper methods used only inside the class are private public class Person private String name = ""; private double score = 0.0; Originally stored first & last name in one instance variable Now we want them separated change instance vars public String tostring() return name; public class Person private String first = ""; private String last = ""; private double score = 0.0; public String tostring() String result = first; result += " "; result += last; return result; 9 Original version, combined names New version, names separated. 10 Non-encapsulated example Getters and setters If instance variables were public: Encapsulation does have a price Client program might use instead of methods public class Person public String first = ""; public String last = ""; public double score = 0.0; public String tostring() String result = first; result += " "; result += last; return result; Non-encapsulated version, instance variables are public. Person p = new Person("Bob Dole"); System.out.println(p.name + " " + p.score); Client program. Changing instance variables causes compile error. Client should have been using tostring() but used instance variable because they were publically available. If clients need access to instance var, must create: getter methods - "get" value of an instance var setter methods - "set" value of an instance var public double getposx() return posx; Getter method. Also know as an accessor method. public void setposx(double x) posx = x; Setter method. Also know as a mutator method. 11 12

Immutable data type Immutability Object's value cannot change once constructed Immutability: Pros and Cons Immutable data type Object's value cannot change once constructed Advantages Avoid aliasing bugs Makes program easier to debug Limits scope of code that can change values Pass objects around without worrying about modification Disadvantage New object must be created for every value 13 14 String immutability: consequences Since String is immutable, this method call cannot change the variable s! String s = "Hello world!"; System.out.println("before : " + s); s.touppercase(); System.out.println("after : " + s); before : Hello world! after : Hello world! String s = "Hello world!"; System.out.println("before : " + s); s = s.touppercase(); System.out.println("after : " + s); before : Hello world! after : HELLO WORLD! 15 Final Final access modifier Declaring variable final means that you can assign value only once, in initializer or constructor public class Counter private final String name; private int count; Advantages Helps enforce immutability This value doesn't change once the object is constructed This value can change in instance methods Prevents accidental changes Makes program easier to debug Documents that the value cannot not change 16

Equality: integer primitives Boolean operator == See if two variables are exactly equal i.e. they have identical bit patterns Boolean operator!= See if two variables are NOT equal i.e. they have different bit patterns Equality: floating-point primitives Floating-point primitives i.e. double and float Only an approximation of the number Use == and!= at your own peril double a = 0.1 + 0.1 + 0.1; double b = 0.1 + 0.1; double c = 0.0; if (a == 0.3) System.out.println("a is 0.3!"); int a = 5; if (a == 5) System.out.println("yep it's 5!"); while (a!= 0) a--; This is a safe comparison since we are using an integer type. if (b == 0.2) System.out.println("b is 0.2!"); if (c == 0.0) System.out.println("c is 0.0!"); b is 0.2! c is 0.0! 17 18 Equality: floating-point primitives Floating-point primitives i.e. double and float Only an approximation of the number Use == and!= at your own peril Equality: reference variables Boolean operator ==,!= Compares bit values of remote control Not the values stored in object's instance variables Usually not what you want double a = 0.1 + 0.1 + 0.1; double b = 0.1 + 0.1; double c = 0.0; final double EPSILON = 1e-9; if (Math.abs(a - 0.3) < EPSILON) System.out.println("a is 0.3!"); if (Math.abs(b - 0.2) < EPSILON) System.out.println("b is 0.2!"); if (Math.abs(c) < EPSILON) System.out.println("c is 0.0!"); a is 0.3! b is 0.2! c is 0.0! Ball b = new Ball(0.0, 0.0, 0.5); Ball b2 = new Ball(0.0, 0.0, 0.5); System.out.println("balls equal!"); b = b2; System.out.println("balls now equal!"); 19 20

Equality: reference variables Ball b = new Ball(0.0, 0.0, 0.4); Ball b2 = new Ball(0.0, 0.0, 0.5); r=0.4 r=0.5 Object equality Implement equals() instance method Up to class designer exactly how it works Client needs to call equals(), not == or!= System.out.println("balls equal!"); b = b2; System.out.println("balls now equal!"); balls now equal b r=0.4 b b2 r=0.5 b2 public class Ball // See if this Ball is at the same location and radius // as some other Ball (within a tolerance of 1e-10). // Ignores the color. public boolean equals(ball other) final double EPSILON = 1e-9; return ((Math.abs(posX - other.posx) < EPSILON) && (Math.abs(posY - other.posy) < EPSILON) && (Math.abs(radius - other.radius) < EPSILON)); 21 22 Equality: String variables Boolean operator ==,!= Compares bit values of remote control A String is a reference variable Does not compare text stored in the String objects Usually not what you want String a = "hello"; String b = "hello"; String c = "hell" + "o"; String d = "hell"; d = d + "o"; if (a == b) System.out.println("a equals b!"); if (b == c) System.out.println("b equals c!"); if (c == d) System.out.println("c equals d!"); a equals b! b equals c! Handy String methods String is an object with lots of methods: Method int length() char charat(int index) String substring(int start, int end) boolean equals(string other) How many characters in this string char value at specified index Substring [start, end - 1] inclusive Is this string the same as another? boolean equalsignorecase(string other) Is this string the same as another ignoring case? String trim() String tolowercase() String touppercase() int indexof(string str) int indexof(string str, int from) Remove whitespace from start/end Return new string in all lowercase Return new string in all uppercase Index of first occurrence of specified substring, -1 if not found Index of next occurrence of substring starting from index from, -1 if not found 23 24

Equality: String variables Check equality with equals() method Each letter must be the same (including case) String a = "hello"; String b = "hello"; String c = "hell" + "o"; String d = "hell"; d = d + "o"; if (a.equals(b)) System.out.println("a equals b!"); if (b.equals(c)) System.out.println("b equals c!"); if (c.equals(d)) System.out.println("c equals d!"); a equals b! b equals c! c equals d! Summary Object oriented programming Data encapsulation Important consideration when designing a class Access modifiers decide who can see what Immutability, preventing change to a variable Equality Usually avoid == or!= with floating-point types Usually avoid == or!= with reference types Including String Implement or use the equals() method 25 26