A Founda4on for Programming

Similar documents
A Foundation for Programming

3.1 Objects 7/29/2014 1:49:50 PM

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

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

Encapsula)on CMSC 202

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

Objec,ves. Review: Object-Oriented Programming. Object-oriented programming in Java. What is OO programming? Benefits?

26/3/ Creating Data Types. Data Type. Defining Data Types in Java. Point Charge Data Type. Charge Data Type: A Simple Client

Writing a Fraction Class

Processing/Java Syntax. Classes, objects, arrays, and ArrayLists

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Condi(onals and Loops

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

Chapter 4 Defining Classes I

Methods. Methods. Mysteries Revealed

Programming Language Concepts: Lecture 2

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Object Oriented Programming in C#

BBM 102 Introduc0on to Programming II Spring 2014

Programming Language Concepts: Lecture 2

Chapter 12 Object-Oriented Programming. Starting Out with Games & Graphics in C++ Tony Gaddis

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

Programming Languages and Techniques (CIS120)

Chapter 6 Introduction to Defining Classes

CS 251 Intermediate Programming Methods and Classes

Anatomy of a Class Encapsulation Anatomy of a Method

CS 251 Intermediate Programming Methods and More

Learning objec<ves. Classes, Objects, and Methods. Problem Decomposi<on. Problem Decomposi<on (cont d)

Array Basics: Outline

Using data types Fundamentals of Computer Science Keith Vertanen Copyright 2013

Programming Languages and Techniques (CIS120)

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Cpt S 122 Data Structures. Introduction to C++ Part II

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Comments are almost like C++

Fundamental Concepts and Definitions

Classes and Objects. CGS 3416 Spring 2018

CLASSES AND OBJECTS IN JAVA

Classes and Objects Miscellany: I/O, Statics, Wrappers & Packages. CMSC 202H (Honors Section) John Park

Classes & Objects CMSC 202

Array Basics: Outline

Lecture 7. Log into Linux New documents posted to course webpage

CHAPTER 7 OBJECTS AND CLASSES

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

method method public class Temperature { public static void main(string[] args) { // your code here } new

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B

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

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

Methods and Data (Savitch, Chapter 5)

Objects and Classes. Basic OO Principles. Classes in Java. Mark Allen Weiss Copyright 2000

ECE 122. Engineering Problem Solving with Java

CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I

Chapter 4. Defining Classes I

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

ECOM 2324 COMPUTER PROGRAMMING II

Why OO programming? want but aren t. Ø What are its components?

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Defining Classes and Methods

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Operator overloading: extra examples

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 7 OBJECTS AND CLASSES

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

CIS 190: C/C++ Programming. Classes in C++

Lecture 5: Methods CS2301

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Computer Science. 9. Creating Data Types. Computer Science COMPUTER SCIENCE. Section 3.2.

by Pearson Education, Inc. All Rights Reserved. 2

Object Oriented Modeling

Abstract Data Types. Different Views of Data:

5. Defining Classes and Methods

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

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

Objectives. Defining Classes and Methods. Objectives. Class and Method Definitions: Outline 7/13/09

Abstraction in Software Development

Programming 2. Object Oriented Programming. Daniel POP

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

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

Defining Classes and Methods

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

CS251L REVIEW Derek Trumbo UNM

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

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

10. Java Classes. Classes - Technical. Example: Earthquake catalog. Classes - Conceptual

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Lecture 3. Lecture

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

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

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

Object-Oriented Programming Concepts

Programming by Delegation

System.out.print(); Scanner.nextLine(); String.compareTo();

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Transcription:

3.1 Objects LOGO STYLE GUIDE Schools within the University Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 3/16/14 11:29 PM

A Founda4on for Programming any program you might want to write objects func4ons and modules graphics, sound, and image I/O arrays condi4onals and loops create your own data types Math primi4ve data types text I/O assignment statements 2

Data Types Data Types: set of values and associated opera4ons Primi4ve Types: values map directly to the machine representa4on ops map directly to machine instruc4ons Data Type boolean int double Set of Values true, false - 2 31 to 2 31-1 any of 2 64 possible reals Opera4ons not, and, or, xor add, subtract, mul4ply add, subtract, mul4ply We want to write programs that handle other data types colors, pictures, strings, input streams, complex numbers, vectors, matrices, polynomials, points, polygons, charged par4cles, celes4al bodies, 3

Objects Objects: represent values and opera4ons for more complex data types Object variables are called fields Object opera4ons are called methods Data Type Color Set of Values 24 bits Opera4ons get red component, brighten Picture 2D array of colors get/set color of pixel (i, j) String sequence of characters length, substring, compare Objects are said to encapsulate (hide) its detail How an object is implemented is not important What it does is important Objects can be created and referenced with variables 4

Object- Oriented Programming Programming paradigm that views a program as a collec4on of interac4ng objects In contrast, the conven4onal model views the program as a list of tasks (subrou4nes or func4ons) We ll talk about how to: Create your own data types (set of values and opera4ons) Use objects in your programs (e.g., manipulate objects) Why would I want to use objects in my programs? Simplify your code Make your code easier to modify Share an object with a friend 5

The String Object Fields:??? Methods: boolean equals(string anotherstring) int length() String substring(int beginidx, int endidx) String tolowercase() String touppercase()... http://download.oracle.com/javase/1.4.2/docs/api/

Constructors and Methods To construct a new object: Use keyword new (to invoke constructor) Use name of data type (to specify which type of object) with associated parameters for the constructor To apply an opera4on: Use name of object (to specify which object) Use the dot operator (to access a member of the object) Use the name of the method (to specify which opera4on) 7

Defining Your Own Objects with Classes Classes are blueprints or prototypes for new objects Classes define all field and method declara4ons which are repeated for each new object created Using a class to create a new object is called instan2a2ng an object crea4ng a new object instance of the class Classes o_en model real- world items

Bouncing Ball Object What do we want to have the ball do? (i.e., what methods should it have?) What ini4al parameters should we specify in the constructor? 9

Bouncing Ball Object What do we want to have the ball do? (i.e., what methods should it have?) void draw() : Ball, draw thyself! void update() : simulate the ball s mo4on What ini4al parameters should we specify in the constructor? 10

Bouncing Ball Object What do we want to have the ball do? (i.e., what methods should it have?) void draw() : Ball, draw thyself! void update() : simulate the ball s mo4on What ini4al parameters should we specify in the constructor? Ball() : creates a ball at a random loca4on Ball (int x, int y) : creates a ball at (x, y) These methods cons4tute the ball s API 11

Bouncing Ball Object Given only the API, we can use the object in a program: static Ball[] balls = new Ball[20]; public void setup() { size(500, 500); // Create all new Ball objects for (int i = 0; i < balls.length; i++) { balls[i] = new Ball(); public void draw() { background(255); Declare an array of Balls. New objects are created with the new keyword. Ball ------------------ Ball() Ball(int x, int y) void draw() void update() for (int i = 0; i < balls.length; i++) { balls[i].update(); balls[i].draw(); Methods of objects stored in the array are accessed using dot-notation. 12

Bouncing Ball Object Implementa4on What fields should the ball have? (i.e., what does it need to know about itself?) Let s start by implemen4ng the constructor, then proceed to the methods... 13

Bouncing Ball Object Implementa4on What fields should the ball have? (i.e., what does it need to know about itself?) posi4on (x,y) velocity (dx, dy) accelera4on due to gravity (ay) size, color, etc... Let s start by implemen4ng the constructor, then proceed to the methods... 14

Defining Your Own Objects with Classes // Defining a new object public class MyObjectName { // All field variable declarations go here. // Field variables should be private. /* Define a special function-like statement called * the object s constructor. * Its name is same as the class name, * with no return value. */ public MyObjectName( optional arguments ) { // Perform all initialization here // Declare all method functions here 15

// A Ball Class (place inside main application class) class Ball { // Fields private double ay = 0.02; private double x; private double y; private double dx; private double dy; private double radius = 10; // y acceleration (gravity) // x position // y position // x velocity // y velocity // Constructor public Ball() { x = StdRandom.uniform(radius, width - radius); y = StdRandom.uniform(0, 0.5 * height); dx = StdRandom.uniform(-1, 1); dy = 0;... 16

// Methods public void update() { // Move ball x += dx; y += dy; dy += ay; // Bounce off walls and floor if (x < radius x > (width radius)) { dx = -dx; if (y > height - radius) { dy = -0.9*dy; y = height - radius; public void draw() { float d = (float) radius * 2; ellipse((float) x, (float) y, d, d); 17

Where to Write Your Class When using Processing... Write an outer class that extends PApplet Place all classes with graphical objects inside this outer class These inner classes should not be declared public Otherwise Your classes can be standalone classes, defined in their own files They should be declared public 18

Comparing Declara9ons and Ini9alizers int i; int j = 3; float f = 0.1; float[] f2 = new float[20]; String s1 = "abc"; String s2 = new String("abc"); Ball b = new Ball(); Ball[] b2 = new Ball[20]; for (int i = 0; i < b2.length; i++) { b2[i] = new Ball();

Object References Allow client to manipulate an object as a single en4ty Essen4ally a machine address (pointer) Ball b1 = new Ball(); b1.update(); b1.update(); Ball b2 = new Ball(); b2.update(); b2 = b1; b2.update(); addr value C0 0 C1 0 C2 0 C3 0 C4 0 C5 0 C6 0 C7 0 C8 0 C9 0 CA 0 CB 0 CC 0 main memory (64-bit machine) 20

Object References Allow client to manipulate an object as a single en4ty Essen4ally a machine address (pointer) Ball b1 = new Ball(); b1.update(); b1.update(); Ball b2 = new Ball(); b2.update(); b2 = b1; b2.update(); b1 C0 addr value C0 0.50 0 C1 0.50 0 C2 0.05 0 C3 0.01 0 C4 0.03 0 C5 0 C6 0 C7 0 C8 0 C9 0 CA 0 CB 0 CC 0 registers main memory (64-bit machine) 21

Object References Allow client to manipulate an object as a single en4ty Essen4ally a machine address (pointer) Ball b1 = new Ball(); b1.update(); b1.update(); Ball b2 = new Ball(); b2.update(); b2 = b1; b2.update(); b1 C0 addr value C0 C1 C2 C3 0.55 0.50 0.50 0.51 0.05 0.01 C4 0.03 C5 0 C6 0 C7 0 C8 0 C9 0 CA 0 CB 0 CC 0 registers main memory (64-bit machine) 22

Object References Allow client to manipulate an object as a single en4ty Essen4ally a machine address (pointer) Ball b1 = new Ball(); b1.update(); b1.update(); Ball b2 = new Ball(); b2.update(); b2 = b1; b2.update(); b1 C0 addr value C0 0.60 0.55 C1 0.51 0.52 C2 0.05 C3 0.01 C4 0.03 C5 0 C6 0 C7 0 C8 0 C9 0 CA 0 CB 0 CC 0 registers main memory (64-bit machine) 23

Allow client to manipulate an object as a single en4ty Essen4ally a machine address (pointer) Ball b1 = new Ball(); b1.update(); b1.update(); Ball b2 = new Ball(); b2.update(); b2 = b1; b2.update(); Object References b1 C0 b2 addr value C0 0.60 C1 0.52 C2 0.05 C3 0.01 C4 0.03 C5 0 C6 0 C7 C7 0.50 0 C8 0.50 0 C9 0.07 0 CA 0.04 0 CB 0.04 0 CC 0 registers main memory (64-bit machine) 24

Object References Allow client to manipulate an object as a single en4ty Essen4ally a machine address (pointer) Ball b1 = new Ball(); b1.update(); b1.update(); Ball b2 = new Ball(); b2.update(); b2 = b1; b2.update(); b1 C0 b2 C7 addr value C0 0.60 C1 0.52 C2 0.05 C3 0.01 C4 0.03 C5 0 C6 0 C7 0.57 0.50 C8 0.50 0.54 C9 0.07 CA 0.04 CB 0.04 CC 0 registers main memory (64-bit machine) 25

Allow client to manipulate an object as a single en4ty Essen4ally a machine address (pointer) Ball b1 = new Ball(); b1.update(); b1.update(); Ball b2 = new Ball(); b2.update(); b2 = b1; b2.update(); Object References C7 CB can be reused for other variables. Known as garbage collec4on in java. b1 C0 b2 C0 registers addr value C0 0.60 C1 0.52 C2 0.05 C3 0.01 C4 0.03 C5 0 C6 0 C7 0.57 C8 0.54 C9 0.07 CA 0.04 CB 0.04 CC 0 main memory (64-bit machine) 26

Allow client to manipulate an object as a single en4ty Essen4ally a machine address (pointer) Ball b1 = new Ball(); b1.update(); b1.update(); Ball b2 = new Ball(); b2.update(); b2 = b1; b2.update(); Object References Moving b2 also moves b1 since they are aliases that reference the same object. b1 C0 b2 C0 registers addr C0 value 0.65 0.60 C1 0.52 0.53 C2 0.05 C3 0.01 C4 0.03 C5 0 C6 0 C7 0.57 C8 0.54 C9 0.07 CA 0.04 CB 0.04 CC 0 main memory (64-bit machine) 27

Pass- By- Value Arguments to methods are always passed by value. Primi4ve types: passes copy of value of actual parameter. Objects: passes copy of reference to actual parameter. public class PassByValue { static void update(int a, int[] b, String c) { a = 7; b[3] = 7; c = "seven"; StdO.println(a + " " + b[3] + " " + c); public static void main(string[] args) { int a = 3; int[] b = { 0, 1, 2, 3, 4, 5 ; String c = "three"; StdOut.println(a + " " + b[3] + " " + c); update(a, b, c); StdOut.println(a + " " + b[3] + " " + c); % java PassByValue 3 3 three 7 7 seven 3 7 three 28

Encapsulation 29

Access Control Encapsulation is implemented using access control. Separates interface from implementation Provides a boundary for the client programmer Visible parts of the class (the interface) can be used and/or changed by the client programmer. Hidden parts of the class (the implementation) Can be changed by the class creator without impacting any of the client programmer s code Can t be corrupted by the client programmer 30

Access Control in Java Visibility modifiers provide access control to instance variables and methods. public visibility - accessible by everyone, in particular the client programmer A class interface is defined by its public methods. private visibility - accessible only by the methods within the class Two others protected and package later 31

Good Programming Practice Combine methods and data in a single class Label all instance variables as private for information hiding The class has complete control over how/when/if the instance variables are changed Fields primarily support class behavior Minimize the class public interface 32

Using this You can think of this as an implicit private reference to the current instance. Date b1 = new Date(); Date === public ==== Date() int getyear()... === private === int month int day int year Date this... b1 C0 registers addr value C0 1 C1 1 C2 1900 C3 C0 C4? C5? C6? main memory (64-bit machine) month day year this Note that b1.year and b1.this.year refer to the same field 34

Overloaded Constructors public class Date { private int month; // 1-12 private int day; // 1-31 private int year; // 4 digits // no-argument constructor public Date() { month = 1; day = 1; year = 1900; // alternative constructor public Date(int month, int day, int year) { this.month = month; this.day = day; this.year = year; // 1 Jan 1900 Date d1 = new Date();... // 30 Oct 2013 Date d2 = new Date(10, 30, 2013); 35

Accessors & Mutator Class behavior may allow access to, or modification of, individual private instance variables. Accessor method retrieves the value of a private instance variable conventional to start the method name with get Mutator method changes the value of a private instance variable conventional to start the name of the method with set Gives the client program indirect access to the instance variables. 36

More Accessors and Mutators Question: Doesn t the use of accessors and mutators defeat the purpose of making the instance variables private? Answer: No The class implementer decides which instance variables will have accessors. Mutators can: validate the new value of the instance variable, and decide whether or not to actually make the requested change. 37

Accessor and Mutator Example public class Date { private int month; // 1-12 private int day; // 1-31 private int year; // 4-digit year // accessors return the value of private data public int getmonth() { return month; // mutators can validate the new value public boolean setmonth(int month) { if (1 <= month && month <= 12) { this.month = month; return true; else // this is an invalid month return false; // rest of class definition follows 38

Accessor/Mutator Caution In general you should NOT provide accessors and mutators for all private instance variables. Recall that the principle of encapsulation is best served with a limited class interface. 39

Private Methods Methods may be private. Cannot be invoked by a client program Can only be called by other methods within the same class definition Most commonly used as helper methods to support top-down implementation of a public method 40

Private Method Example public class Date { private int month; // 1-12 private int day; // 1-31 private int year; // 4-digit year // accessors return the value of private data public int getmonth() { return month; // mutators can validate the new value public boolean setmonth(int month) { if (isvalidmonth(month)) { this.month = month; return true; else // this is an invalid month return false; // helper method - internal use only private boolean isvalidmonth(int month) { return 1 <= month && month <= 12; 41

Static and Final 42

Static Variable A static variable belongs to the class as a whole, not just to one object. There is only one copy of a static variable per class. All objects of the class can read and change this static variable. A static variable is declared with the addition of the modifier static. static int mystaticvariable = 0; Copyright 2008 Pearson Addison- Wesley. All rights reserved 43

Static Constants A sta$c constant is used to symbolically represent a constant value. The declara4on for a sta4c constant includes the modifier final, which indicates that its value cannot be changed: public sta9c final float PI = 3.142; It is not necessary to instan4ate an object to access a sta4c variable, constant or method. When referring to such a constant outside its class, use the name of its class in place of a calling object. float radius = MyClass.PI * radius * radius; Copyright 2008 Pearson Addison- Wesley. All rights reserved 44

Rules for Static Methods Sta4c methods have no calling/host object (they have no this). Therefore, sta4c methods cannot: Refer to any instance variables of the class Invoke any method that has an implicit or explicit this for a calling object Sta4c methods may invoke other sta4c methods or refer to sta4c variables and constants. A class defini4on may contain both sta4c methods and non- sta4c methods. 45

main is a Static Method Note that the method header for main( ) is public static void main(string[] args) Being static has two effects: main can be executed without an object. Helper methods called by main must also be static. 46

Any Class Can Have a main( ) Every class can have a public static method name main( ). Java will execute main in whichever class is specified on the command line. java <classname> A convenient way to write test code for your class. 47

Static Review Given the skeleton class definition below public class C { public int a = 0; public static int b = 1; public void f() { public static void g() { Can body of f() refer to a? Can body of f() refer to b? Can body of g() refer to a? Can body of g() refer to b? Can f() call g()? Can g() call f()? For each, explain why or why not. 48