Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Similar documents
Outline. Turtles. Creating objects. Turtles. Turtles in Java 1/27/2011 TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

We will work with Turtles in a World in Java. Seymour Papert at MIT in the 60s. We have to define what we mean by a Turtle to the computer

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 12 CREATING CLASSES PART 1

Objects in Memory. Objects in Memory. Trace. Trace. Outline TOPIC 13 OBJECTS IN MEMORY, PASSING PARAMETERS

Week 3: Objects, Input and Processing

Media Computation. Lecture 16.1, December 8, 2008 Steve Harrison

CIS133J. Working with Numbers in Java

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Algorithms and Programming I. Lecture#12 Spring 2015

Programming by Delegation

Lecture 5: Methods CS2301

Class #1. introduction, functions, variables, conditionals

MEMORIZE the Java App pick: public class { public static void main(string[] a) {

Software and Programming 1

} Each object in a Java program has an identifier (name) } This includes:

1.00 Lecture 8. Using An Existing Class, cont.

TOPIC 5 INTRODUCTION TO PICTURES

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

STUDENT LESSON A5 Designing and Using Classes

1 Getting started with Processing

CS 231 Data Structures and Algorithms, Fall 2016

Introduction to Java Unit 1. Using BlueJ to Write Programs

AP Computer Science Unit 1. Writing Programs Using BlueJ

TOPIC 5 INTRODUCTION TO PICTURES

Animations involving numbers

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Media Computation. Lecture 15.2, December 3, 2008 Steve Harrison

Pointers and scanf() Steven R. Bagley

Chapter 4 Defining Classes I

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CMSC 150 LECTURE 1 INTRODUCTION TO COURSE COMPUTER SCIENCE HELLO WORLD

Software and Programming 1

CMPT 100 : INTRODUCTION TO

1 Getting started with Processing

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

ITI Introduction to Computing II

The University of Western Ontario Department of Computer Science Computer Science 1026a Midterm Exam 2 hours

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

Grade 6 Math Circles November 6 & Relations, Functions, and Morphisms

Changing a picture. Modifying Pictures. Looping (iteration) Changing all the pixels in a picture TOPIC 6 MODIFYING PICTURES USING LOOPS

Programming Basics. Part 1, episode 1, chapter 1, passage 1

TOPIC 6 MODIFYING PICTURES USING LOOPS

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

St. Edmund Preparatory High School Brooklyn, NY

CISC 1600 Lecture 3.1 Introduction to Processing

Understanding the Screen

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Pace University. Fundamental Concepts of CS121 1

Building Java Programs

CPS122 Lecture: Defining a Class

Topic 1: Introduction

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

AP Computer Science Unit 1. Writing Programs Using BlueJ

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

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

COP 3330 Final Exam Review

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Boolean Expressions. Is Equal and Is Not Equal

Programming Exercise 7: Static Methods

CompSci 125 Lecture 02

Packages. 1. Every Java object resides in a package. 2. An object s package is explicitly declared on the first line of code in a.

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Defining Classes and Methods

Inheritance and Interfaces

TOPIC 8 MORE ON WHILE LOOPS

[ the academy_of_code] Senior Beginners

Mr. Monroe s Guide to Mastering Java Syntax

Topic Notes: Java and Objectdraw Basics

Fall 2017 CISC124 9/16/2017

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Lecture 10: building large projects, beginning C++, C++ and structs

Building Java Programs

LAB: INTRODUCTION TO FUNCTIONS IN C++

Object-Oriented Programming in Processing

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

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.

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Programming with Java

CS Problem Solving and Object-Oriented Programming

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Fundamentals of Programming Session 25

CISC 110 Week 3. Expressions, Statements, Programming Style, and Test Review

Methods CSC 121 Spring 2017 Howard Rosenthal

Variables, expressions and statements

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Welcome to the Primitives and Expressions Lab!

Shorthand for values: variables

Expressions and Casting

TSM Report Designer. Even Microsoft Excel s Data Import add-in can be used to extract TSM information into an Excel spread sheet for reporting.

3.1 Class Declaration

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

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

Transcription:

1 Outline TOPIC 3 INTRODUCTION TO PROGRAMMING Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared by B. Ericson. 2 2 To create objects Using the new operator To declare reference variables In order to refer to objects To learn about object methods Send messages to objects to ask them to do something To create a method to perform a task To learn about class methods 3 Creating objects Making things to program with.

Syntax vs Semantics Creating objects in Java 77 8 8 Syntax means the rules for defining a program, the rules we must follow to make code that compiles In English, syntax would mean putting periods at the end of sentences, not ending sentences with a proposition, starting a sentence with a capital, etc Semantics is the meaning behind what you wrote For example, in English Dog, bread to chair! is syntactically correct, but makes no sense! The semantics aren t right In computer programming, the syntax are the rules for how to type in code so it compiles such as ending statements with a semi colon, or all the orders of words we will see in the next few slides To create an object of a class, we use a special keyword new with the syntax new ClassName(value, value, ); Our turtles example: Our Turtle objects live in a World object So, we must first create a World object, so that our turtles have a place to live How do we create a World object? Creating objects in Java Reference variables 99 10 Let s try typing new World(); This will create a new World object, displayed as : But we will not have any way to refer to it again! Recall: this is why we need variables, so that we can access values later We need to store it in a variable Recall that all variables are declared by type name; But the type of a reference variable is the name of the class, so we declare a reference variable by: Class name; We can declare a reference variable and have it refer to a new object in one statement: Class name = new Class(value, value, ); Creating a new world Creating a new turtle 11 Example: declare a reference variable world1 which refers to a new World object World world1; world1 = new World(); Or in a single statement: World world1 = new World(); world1 World object 12 12 To create a Turtle object, we must specify the World object that it lives in: Turtle turtle1 = new Turtle(world1); It starts off facing north and in the center of the world by default The world starts off with a size of 640 by 480, with no turtles

13 Creating a new turtle 13 14 Wait a sec In that slide, we had: Turtle turtle1 = new Turtle(world1); What is (world1)? Creating several objects You can create several World objects: World world2 = new World(); We don t want the Turtle to have no where to live! So when we make the Turtle, we tell him to live in world1. If we wanted him in world8, we could first make world8, then make the Turtle live there Specifying things to an object when you make it is called using parameters There will be more on this later! You can also create several Turtle objects in one world: Turtle turtle2 = new Turtle(world2); Turtle turtle3 = new Turtle(world2); Note that one turtle is on top of the other (why?) 15 Other ways to create turtles 15 16 Turtles can also be created at different starting positions To start a turtle off at position (30,50) in a world created previously: Turtle turtle4 = new Turtle(30, 50, world2); Now we are telling the turtle to live in world2, and where to start off! Again, using parameters Turtle positions are given as x and y values X starts at 0 on the left and increases horizontally to the right Y starts at 0 at the top of the window and increases to the bottom Turtle basics We can print out the status of our world and our turtles to see what s what: System.out.println(world1); System.out.println(turtle1); Try this: what does it print? Being able to print out the states of objects can be very handy when debugging Java code 17 Object methods How to do things with objects. 18 Actions are called methods in Java Now that we have created Turtle objects, we can perform actions on them An action performed on/by an object is a collection of Java statements called a method More precisely, it is called an object method or instance method We will see something called a class method later

Object methods Defining methods in Java 19 20 A method is a named collection of statements that carry out a specific task Example: a method called forward causes a turtle to move forward a specified distance Example: a method called turnright causes a turtle to turn to the right We can think of an object method as a message sent to an object, to do something Example: send a message to a Turtle object to move forward We define a method by writing the code that performs the action Every method in Java must be defined inside a class Remember, Java is Object Oriented and Objects are written in classes if the method isn t in a class, it doesn t exist! Example: the method forward is defined for the Turtle class We will see what a method definition looks like later Calling methods in Java Calling methods in Java 21 22 We call (invoke) a method from a program when we want it to be executed We can call methods written by others (e.g. the methods forward, turnright, etc. for a turtle) Or methods that we have written ourselves (later) An object method can only be executed on an object belonging to the class in which the method was defined Example: our method forward can only be invoked on objects from the Turtle class Object methods must be executed on an object, using the syntax objectreference.methodname() The object reference is typically the name of an object reference variable Example: turtle1.forward(); 23 Method parameters Methods may take input to act upon Input is passed in to the method in the form of a list of parameters in parentheses, given when the method is invoked, as in methodname( parameter1, parameter2, ); Remember, just like telling the turtle where to live! 24 Return values If a method produces a result, this result is returned by the method to wherever the method was invoked We can think of the result as replacing the invocation of the method Examples upcoming Example of a method call with a parameter : turtle1.forward(50);

Return Values vs Paramters Exercise: methods for strings 25 25 26 An easy way to think of parameters and return values is to think of them like baseball When you call a method, you throw it parameters When its done, it pass you back the return value You throw the method the parameters You It throws you back the return value The method Try the following String example: String name = Harry Potter"; String lowername = name.tolowercase(); System.out.println(lowerName); String uppername = name.touppercase(); System.out.println(upperName); System.out.println(name); Notice that the value of name didn t change Strings are called immutable objects: all String methods that modify a string do not change the original string, but return a new one. Moving a turtle 28 27 Methods for turtles What we can make turtles do! **You ll need these for your first assignment** Turtles can move forward: turtle3.forward(); The default is to move by 100 steps (pixels) You can also tell the turtle how far to move (pass a parameter): turtle2.forward(50); There are corresponding backward() methods to move a turtle backward Turning a turtle Turning a turtle 29 29 30 Turtles can turn Right turtle3.turnright(); turtle3.forward(); Left turtle2.turnleft(); turtle2.forward(50); Turtles can turn by a specified number of degrees A positive number turns the turtle to the right turtle3.turn(90); turtle3.forward(100); A negative number turns the turtle to the left turtle2.turn(-90); turtle2.forward(70);

Turning a turtle The pen 31 31 32 Turtles can turn to face other turtles: turtle2.turntoface(turtle3); turtle3.turntoface(turtle2); Turtles can turn to face specific points: turtle2.turntoface(0,0); turtle3.turntoface(639,479); Each turtle has a pen The default is to have the pen down to leave a trail You can pick the pen up: turtle1.penup(); turtle1.turn(-90); turtle1.forward(70); You can put it down again: turtle1.pendown(); turtle1.forward(100); Drawing a T Drawing a T 33 34 Algorithm (Steps in the process): Create a World variable and a World object, and a Turtle variable and Turtle object Ask the Turtle object to go forward 100 Ask the Turtle object to pick up the pen Ask the Turtle object to turn left Ask the Turtle object to go forward 25 Ask the Turtle object to turn 180 degrees Ask the Turtle object to put down the pen Ask the Turtle object to go forward 50 World world1 = new World(); Turtle turtle1 = new Turtle(world1); turtle1.forward(100); turtle1.penup(); turtle1.turnleft(); turtle1.forward(25); turtle1.turn(180); turtle1.pendown(); turtle1.forward(50); Moving to a location Setting attributes 35 36 A turtle can move to a particular location: turtle1.penup(); turtle1.moveto(500,20); Y X 639 An object method can work with the properties (attributes) of the object on which it was invoked Example: there are methods to set a turtle s width, height, name, etc. turtle1.setwidth(50); 479 turtle1.setheight(30); turtle1.setname( Tiny );

37 Getting attributes There are methods to get a turtle s width, height, etc. int width = turtle1.getwidth(); int height = turtle1.getheight(); System.out.println("This turtle is " + width + "x" + height); These methods produce a result This value is returned by the method to wherever the method was invoked Another way to print the turtle s size: System.out.println("This turtle is " + turtle1.getwidth() +"x" + turtle1.getheight()); 38 Checking and changing size Tripling a turtle s size int width = turtle1.getwidth(); int height = turtle1.getheight(); turtle1.setwidth(width * 3); turtle1.setheight(height * 3); Changing pen width Changing pen color 39 39 40 You can change the width of the trail: World world1 = new World(); Turtle turtle1 = new Turtle(world1); turtle1.setpenwidth(5); turtle1.forward(100); You can set the color of the pen: turtle1.setpencolor(java.awt.color.red); There are predefined colors you can use: java.awt.color.red Classes defined as part of the Java language are documented in the Java Application Programming Interface (Java API) at http://java.sun.com/j2se/1.5.0/docs/api Find the package java.awt A package is a group of related Java classes Find the class Color 41 Using colors It is much easier to specify colors by using the import statement import java.awt.color; Then you can just use the class name Color without needing the name of the package java.awt as well Example: turtle1.setpencolor(color.red); In a Java program, import statements go at the very beginning of the source file 42 Misc. coloring methods You can change the turtle color: turtle1.setcolor(color.blue); You can change the turtle s body color: turtle1.setbodycolor(color.cyan); You can change the turtle s shell color: turtle1.setshellcolor(color.red); These set methods have corresponding get methods to retrieve colors too

Other things to do Objects control their state 43 44 You can have a turtle hide and then later show itself by using turtle1.hide(); turtle1.show(); You can get a turtle s position by using int xpos = turtle1.getxpos(); int ypos = turtle1.getypos(); System.out.println("This turtle is at " + xpos + "," + ypos); In our turtles world, for example, turtles won t move out of the boundaries of the world Try: World world2 = new World(); Turtle turtle2 = new Turtle(world2); turtle2.forward(600); Note that the turtle stopped at the edge of the screen and did not go any further Creating methods 46 45 Writing your own object methods We are not restricted to just using methods provided by Java or by other programmers We can write our own methods (so cool!) Remember: How to customize code to make it do what YOU want A method is a collection of Java statements that performs some task A method must be defined within a class 47 Defining a method The syntax for defining a method is visibility returntype name(parameterlist) { body of method (statements) } Visibility, returntype and name lets look into these a little closer!: determines access to the method Usually public (all access) or private (just within this class) returntype: is the type of thing returned If nothing is returned, use the keyword void name: start with a lowercase word and uppercasing the first letter of each additional word 48 48 Visibility Determines who (and what) can use your method In other words, determines access to the method Usually its either public (anywhere in the program can use it) or private only other methods in that class can use it

49 Visibility Lets practice 49 50 Class Cell Class Body pubilc void grow(){} public void move(){} private void eat(){} public void standup(){} private void talk(){} Return Type Here we say the type of what will be thrown back at us For instance, if you ask the turtle what size its pen is, it will return an int to the size of the pen is an integer, so the type of the thing it returns is int **If nothing is being returned, the return type is void** Can the body tell the cell to grow? To eat? Can the cell tell the body to talk? To move? 51 Name 51 52 This is the name of the method you are using, what you want to call it For example, if you are writing a method for a turtle to go forward, you might name it moveforward, but you probably wouldn t name it watermellon YOU get to pick the name, it is NOT a keyword There are some rules though: start with a lowercase word and uppercasing the first letter of each additional word Example: drawing a square public void drawsquare() { this.forward(30); this.forward(30); this.forward(30); this.forward(30); } The visibility is public void: this method doesn t return a value The method name is drawsquare There are no parameters Notice that the parentheses are still required The keyword this refers to the object this method is invoked on Adding a method to a class Trying the method 53 54 1. Open file Turtle.java 3. Compile 2. Type the method before the last } // end Compiling resets the Interactions pane, so you will need to create a world and turtle again: World world1 = new World(); Turtle turtle1 = new Turtle(world1); turtle1.forward(50); turtle1.drawsquare(); turtle1.turn(30); turtle1.drawsquare(); This has the turtle draw two squares using the new drawsquare() method we added to the Turtle class What if we want to draw a square that is not 30 by 30?

Adding a parameter Trying the better drawsquare 55 56 public void drawsquare(int width) { } Defining a parameter list specifies the values passed in to the method for each parameter, give its type and the variable name used for it within the method There is only one parameter for this method Its type is int Its name is width Type the following in the Interactions pane: World world1 = new World(); Turtle turtle1 = new Turtle(world1); turtle1.forward(50); turtle1.drawsquare(30); turtle1.turn(30); turtle1.drawsquare(50); What values are passed to the drawsquare method here? When we invoke a method, the parameters passed to the method are called actual parameters How does it work? How does it work? 57 58 What happens when you ask turtle1 to drawsquare(30) by turtle1.drawsquare(30); Java will check the Turtle class to see if it has a method drawsquare that has an int parameter The actual parameter 30 will be copied to the parameter variable width Java will start executing the code in drawsquare The this in the method s code refers to turtle1 (the object the method was invoked on) Now consider turtle1.drawsquare(50); When the drawsquare method is executed, What will be the value of the parameter width? What will this refer to? Now add this to the Interactions pane: Turtle turtle2 = new Turtle(world1); turtle2.drawsquare(40); When the drawsquare method is executed, What will be the value of the parameter width? What will this refer to? Tracing with pictures In the drawsquare method 59 World world1 = new World(); Turtle turtle1 = new Turtle(world1); World object 60 public void drawsquare(int width) { In drawsquare() 30 width this world1 turtle1 Turtle object turtle1 Turtle object turtle1.drawsquare(30); } world1 World object

61 Comments in Java Code To make code more easily understandable, Java allows you to put comments in your code Comments are ignored by the Java compiler But are useful to people reading Java code Commenting code is good programming practice! Java allows commenting in two ways: /* Everything between these symbols is a comment */ // Everything on the line following the double // slash is a comment 62 Example /* Method to draw a square of a specified width: * turtle starts at top left corner of square * and ends where it started, facing the same way */ public void drawsquare(int width) { } 63 Sample problems Create a method for drawing a rectangle Pass in the width and height Create a method for drawing an equilateral triangle All sides have the same length Pass in the length Create a method for drawing a diamond Create a method for drawing a house Using the other methods 64 Class methods Send a message to a class, you do NOT need an object! 65 Class methods in Java Class method (static method) Can be thought of as a message sent to a class, to do something Does not pertain to a particular object belonging to the class 66 Calling class methods Recall that object methods must be executed on an object, using the syntax objectreference.methodname() Class methods are invoked by giving the class name, using the syntax ClassName.methodName()

67 Example Java has a predefined class called Math Find the Java API documentation for the class Math at http://java.sun.com/j2se/1.5.0/docs/api It contains methods for performing basic numeric operations such as square root, trigonometric functions, rounding, etc. Math.round(2.95) The round method rounds a floating point number to the nearest integer It takes a float parameter and returns the int value that is the closest integer 68 Return values If a method produces a result, this result is returned by the method to wherever the method was invoked Example: the sqrt method of class Math returns the positive square root of a double value Example: what will be printed by System.out.println(Math.sqrt(9.0)); We can think of the result as replacing the invocation of the method Sample problem Class methods vs. object methods 69 For the class Math, find the documentation for the methods min, max, random Try the following method calls in the Interactions pane: Math.max(10, 100) Math.min(10,100) Math.random() 70 In the Java API documentation, how can you tell which are class methods and which are object methods? Look for the keyword static on the method If it has the keyword static, then it is a class method No object needs to be created in order to call the method If there is no keyword static, then it is an object method You need an object before you can invoke it 71 The main method In Java there is a special method called the main method Every program that you want to run must have a main method Execution of a Java program always starts with the main method The main method must be defined within some class 72 The main method The main method definition starts with public static void main(string[] args) static because it is not invoked on any object void because it returns nothing (It takes one String array parameter which we will not use)

73 The main method 73 74 74 Woah woah woah What is this: String[] args Remember how we can send a parameter? The main method also gets a parameter! It gets some string parameters. The square brackets [] are a signal to the program that it is getting an array of strings, not just one. We will learn what an array is in the next lecture. The main method Recall that in DrJava Interactions pane: used to try out (practice) individual expressions and statements Definitions pane: used to type in a complete Java program that will be compiled and run There must be a main method in one of the classes Execution starts at the beginning of the main method You should always include this in your main method! Examples Summary: Java Concepts 75 75 You have actually used main methods in the programs you typed in, in the labs Lab 1: programs TryDrJava and MyName Lab 2: program CentigradeToFahrenheit 76 Creating objects Declaring reference variables Object methods Invoking methods Passing parameters Writing methods Comments Class methods The main method Key Notes 77 77 Make sure you know how to: Make a new object (slide 8) Call a method on an object (slide 22) Define a method (slide 47) Object methods must be in the object class Static methods do not need to be called on an object