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

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

CLASSES AND OBJECTS. Fundamentals of Computer Science I

CLASSES AND OBJECTS. Fundamentals of Computer Science I

A Founda4on for Programming

Condi(onals and Loops

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

The life and death of objects, sta2cs. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

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

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

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

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

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

Programming Languages and Techniques (CIS120)

CSCI 135 Midterm Fundamentals of Computer Science I Fall 2011

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

More on inheritance CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014

Variables and data types

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Sta$cs and forma.ng numbers

Designing data types. Fundamentals of Computer Science I

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Libraries, clients, prin/

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Object-Oriented Programming Concepts

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

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Object Oriented Design: Building a Fraction Class

Fundamentals of Programming Data Types & Methods

Introduction to Programming Using Java (98-388)

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

JAVA MOCK TEST JAVA MOCK TEST II

PROGRAMMING FUNDAMENTALS

Introduction to Java

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

A Foundation for Programming

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Chapter 8. Classes and Objects

Exam 1 - (20 points)

Selected Questions from by Nageshwara Rao

Lecture 07, Fall 2018 Wednesday September 19

JAVA GUI PROGRAMMING REVISION TOUR III

Program Fundamentals

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Java Classes & Primitive Types

Java Classes & Primitive Types

Classes & Objects CMSC 202

Inheritance and objects

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

CSC 1214: Object-Oriented Programming

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

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Lecture Set 4: More About Methods and More About Operators

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Another IS-A Relationship

Making New instances of Classes

Using data types Fundamentals of Computer Science Keith Vertanen Copyright 2013

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

Array. Prepared By - Rifat Shahriyar

Building a fraction class.

Interfaces and itera-on. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Introduction to Java Programming

CS 231 Data Structures and Algorithms, Fall 2016

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Options for User Input

Programming Languages and Techniques (CIS120)

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

Java Identifiers, Data Types & Variables

Object-Oriented Programming

COMP 202 Java in one week

CS2141 Software Development using C/C++ C++ Basics

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

Expressions & Flow Control

CS 302 Week 9. Jim Williams

Object Oriented Programming

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

CHAPTER 7 OBJECTS AND CLASSES

Programming Basics. Digital Urban Visualization. People as Flows. ia

Lecture Set 4: More About Methods and More About Operators

Simple Java Reference

Visual Programming. Lecture 2: More types, Methods, Conditionals

CSCI 355 LAB #2 Spring 2004

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

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

Getting started with Java

Zheng-Liang Lu Java Programming 45 / 79

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal

Implemen'ng abstract data types. CSCI 135: Fundamentals of Computer Science Keith Vertanen

Transcription:

Classes and objects Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates Fundamentals of Computer Science Keith Vertanen Copyright 2013

A founda4on for programming any program you might want to write objects func4ons and modules build even bigger programs and reuse code hip://www.flickr.com/photos/vermegrigio/5923415248/ graphics, sound, and image I/O arrays condi4onals and loops Math primi4ve data types text I/O assignment statements 2

Overview Primi4ve types Crea4ng your own data types Classes Objects Instance variables Instance methods Constructors Arrays of objects 3

Java primi4ve types Java type what it stores examples byte short int long 4ny integer values - 128 to 127 small integer values - 32768 to 32767 integer values - 2,147,483,648 to 2,147,483,647 big integer values - 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 3-87 - 3433 123 42 1234 5454-43984938 double floa4ng- point values 9.95 3.0e8 float less precise floa4ng- point values 9.95f 3.0e8f boolean truth values true false char characters 'a', 'b', '!' 4

Primi4ve types Primi4ve type limita4ons Limited to basic set of opera4ons Example: int data type opera4ons: add, subtract, mul4ple, divide, modulo Can't combine related informa4on together in one package Example: need two double's to represent your Mars lander's posi4on, another two for velocity, etc. Example: three parallel arrays to track eas4ng, northing, and call sign of airplanes in RadarContacts 5

Your own types Create your our own types Class Blueprint for a custom data type Object Instance of a class May be mul4ple objects for a par4cular class blueprint Objects have a set of things they know Lander's posi4on, velocity Objects have a set of things they can do Draw the lander Update lander's posi4on using its current velocity See if the lander is out of fuel 6

Let's build a simple class Goal: represent a ball in 2D What does a ball need to know? x- coordinate y- coordinate radius What can a ball do? Draw itself Print out its posi4on and radius 0.1, 0.5 r=0.1 0.7, 0.7 r=0.2 7

Sebng up the Ball class Create Ball.java containing Ball class Add instance variables for what a Ball knows public class Ball private double posx = 0.0; private double posy = 0.0; private double radius = 0.0; instance variables: variables declared inside class but outside any method access modifier: private = only methods in this class can see and change these instance variables We almost always declare our instance variables as private. 8

Adding an instance method Add instance methods for what a Ball can do public class Ball private double posx = 0.0; private double posy = 0.0; private double radius = 0.0; public void draw() StdDraw.filledCircle(posX, posy, radius); instance variables: available (in scope) in any instance method of Ball public String tostring() return "(" + posx + ", " + posy + ") r = " + radius; 9

Adding an instance method Add instance methods for what a Ball can do public class Ball private double posx = 0.0; private double posy = 0.0; private double radius = 0.0; public void draw() StdDraw.filledCircle(posX, posy, radius); tostring() Special method, called whenever object printed with System.out.println public String tostring() return "(" + posx + ", " + posy + ") r = " + radius; instance methods: declared without the static keyword 10

Let's try out our new class! Instan4a4ng objects Like arrays, we must declare and create using new public class BallClient public static void main(string [] args) Ball big = new Ball(); Ball small = new Ball(); big.draw(); small.draw(); "Build me a Ball object, I'm not sending you any input about how to do it." System.out.println("big: " + big); System.out.println("small: " + small); 11

Let's try out our new class! Instan4a4ng objects Like arrays, we must declare and create using new public class BallClient public static void main(string [] args) Ball big = new Ball(); Ball small = new Ball(); big.draw(); small.draw(); System.out.println("big: " + big); System.out.println("small: " + small); % java BallClient big: (0.0, 0.0) r = 0.0 small: (0.0, 0.0) r = 0.0 12

Hello constructors Add a constructor method, sets instance vars public class Ball private double posx = 0.0; private double posy = 0.0; private double radius = 0.0; public Ball(double x, double y, double r) posx = x; posy = y; radius = r; constructor: No return type. Method name same as class. These are requirements! public void draw() StdDraw.filledCircle(posX, posy, radius); public String tostring() return "(" + posx + ", " + posy + ") r = " + radius; 13

BallClient take two Constructor called when we new objects public class BallClient public static void main(string [] args) Ball big = new Ball(0.7, 0.7, 0.2); Ball small = new Ball(0.1, 0.5, 0.1); big.draw(); small.draw(); System.out.println("big: " + big); System.out.println("small: " + small); % java BallClient big: (0.1, 0.5) r = 0.1 small: (0.7, 0.7) r = 0.2 14

Colored balls Goal: make each Ball object have a color specified by an red- green- blue (RGB) value Call StdDraw.setPenColor() in draw() Create a new Color object for a given RGB value Color is a class in the Java API Default color for our Ball objects: mauve 15

import java.awt.*; Ball in living color public class Ball private double posx = 0.0; private double posy = 0.0; private double radius = 0.0; private Color color = new Color(0.88f, 0.68f, 1.0f); public Ball(double x, double y, double r) posx = x; posy = y; radius = r; public void draw() StdDraw.setPenColor(color); StdDraw.filledCircle(posX, posy, radius);... 16

Allowing clients to change color import java.awt.*; public class Ball private double posx = 0.0; private double posy = 0.0; private double radius = 0.0; private Color color = new Color(0.88f, 0.68f, 1.0f); public Ball(double x, double y, double r) posx = x; posy = y; radius = r; public void setcolor(double r, double g, double b) color = new Color((float) r, (float) g, (float) b);... 17

Client sebng random color public class BallClient public static void main(string [] args) Ball big = new Ball(0.7, 0.7, 0.2); Ball small = new Ball(0.1, 0.5, 0.1); big.setcolor(math.random(), Math.random(), Math.random()); small.setcolor(math.random(), Math.random(), Math.random()); big.draw(); small.draw(); System.out.println("big: " + big); System.out.println("small: " + small); 18

Crea4ng lots of balls We can have an array of objects Step 1: create an array to hold Ball objects Ball [] balls = new Ball[7]; balls[0] balls[1] balls[2] balls[3] balls[4] balls[5] balls[6] balls 19

The value null What is in each loca4on of the array? Special value null Default value for reference types (non- primi4ves) Like an unprogrammed remote control Ball [] balls = new Ball[7]; null null null null null null null balls[0] balls[1] balls[2] balls[3] balls[4] balls[5] balls[6] balls 20

Crea4ng all the Ball objects Each array loca4on needs a new object Ball [] balls = new Ball[7]; for (int i = 0; i < balls.length; i++) balls[i] = new Ball(Math.random(), Math.random(), Math.random() * 0.2); balls[i].setcolor(math.random(), Math.random(), Math.random()); balls[0] balls[1] balls[2] balls[3] balls[4] balls[5] balls[6] balls 21

Client to draw lots of Ball objects public class BallClientDeluxe public static void main(string[] args) Ball [] balls = new Ball[Integer.parseInt(args[0])]; for (int i = 0; i < balls.length; i++) balls[i] = new Ball(Math.random(), Math.random(), Math.random() * 0.2); balls[i].setcolor(math.random(), Math.random(), Math.random()); balls[i].draw(); % java BallClientDeluxe 100 22

Overlap detec4on Goal: draw many Ball objects without overlap When do two balls overlap? (x1, y1) r1 (x2, y2) r2 Euclidean distance between centers: d = (x1 - x2) 2 + (y1 - y2) 2 Balls overlap if: d < (r1 + r2) 23

Implemen4ng overlap detec4on Overlap detec4on is something a Ball can do We can add a method to Ball class for this! (x1, y1) r1 (x2, y2) r2 Euclidean distance between centers: d = (x1 - x2) 2 + (y1 - y2) 2 Balls overlap if: d < (r1 + r2) public boolean overlap(ball other) double deltax = posx - other.posx; double deltay = posy - other.posy; double d = Math.sqrt(deltaX * deltax + deltay * deltay); if (d < (radius + other.radius)) return true; return false; 24

BallClientSuperDeluxe public class BallClientSuperDeluxe public static void main(string[] args) Ball [] balls = new Ball[Integer.parseInt(args[0])]; for (int i = 0; i < balls.length; i++) boolean overlap = false; do balls[i] = new Ball(Math.random(), Math.random(), Math.random() * 0.2); int j = 0; overlap = false; while ((j < i) && (!overlap)) overlap = balls[i].overlap(balls[j]); j++; while (overlap); balls[i].setcolor(math.random(), Math.random(), Math.random()); balls[i].draw(); 25

26

Summary Crea4ng your own data types Object- oriented programming (OOP) Design classes encapsula4ng: What objects know What objects can do Prevalent concept in most modern programming languages 27