Introduction to ObjectOriented Programming Lesson 2 Classes and

Introduction to Object-Oriented Programming Lesson 2: Classes and Instances Data Types Object Interactions Tracing Slide 1

Review Slide 2

Classes and Objects Components are objects. The programmer determines the attributes and methods needed, and then creates a class. A class is a collection of programming statements that define the required object A class as a “blueprint” that objects may be created from. An object is the realization (instantiation) of a class in memory. Classes can be used to instantiate as many objects as are needed. Each object that is created from a class is called an instance of the class. A program is simply a collection of objects that interact with each other to accomplish a goal. Slide 3

Key Concept: Class vs. Instance Class § Think: generic concept Instance (aka Object) § Think: physical object § The concept of a circle § The green circle with a 4 cm diameter on my shirt § The concept of a car § My blue Nissan minivan with the dent on the side § The concept of a giraffe § Stella, the female giraffe who lives at the Philadelphia zoo Slide 4

Classes specify types of data object store and types of actions the objects can do DATA aka “attributes” aka “state” For example: § Circle data: Diameter, color, (x, y) location, visibility … § Car data: Make, model, year, color … § Giraffe data: Height, weight, birthday, name … ACTIONS aka “methods” aka “functions” Object Attributes (data) For example: § Circle methods: move. Down(), change. Size(), make. Visible() … § Car methods: start. Engine(), reverse(), set. Color() … § Giraffe methods: eat(), walk(), sleep(), set. Weight() … Methods (behaviors / procedures) Slide 5

Methods and parameters 5 -6 Objects have operations which can be invoked (Java calls them methods). Methods may have parameters to pass additional information needed to execute. Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling Slide 6

Other observations 8 Many instances can be created from a single class. An instance has attributes: values stored in fields. The class defines what fields an instance has, but each instance stores its own set of values (the state of the instance). Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling Slide 7

State Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling 8 -9 Slide 8

Two circle objects Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling 10 Slide 9

Programming Languages Sample Program Curly braces mark off a block of code public class Hello. World { public static void main(String[] args) { String message = "Hello World"; System. out. println(message); } } Key words in the sample program are: • public • static • class • void Key words are lower case (Java is a case sensitive language). Key words cannot be used as a programmer-defined identifier. Semi-colons are statement terminators and are used to end Java statements; however, not all lines of a Java program end a statement. Part of learning Java is to learn where to properly use the punctuation. Slide

Programming Languages Lines vs Statements There are differences between lines and statements when discussing source code. System. out. println( message); This is one Java statement written using two lines. Do you see the difference? A statement is a complete Java instruction that causes the computer to perform an action. Slide

Getting picky with terminology Slide

Terminology Check Class versus Object versus Instance § Class is a “template” / “blueprint” that is used to create objects § Objects have two main characteristics – state and behavior. An object stores its state in fields and exposes its behavior through methods. § An instance is a unique copy of a Class. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance. Technically both classes and instances are objects. § An instance is an instantiated object derived from a class § my. Square = new Square(); § Any Class in Java is actually derived from a class called Object (like objects such as arrays) § Many elements of Java are objects. Slide

Terminology Check Instance Variable vs. Field vs. Property vs. Attribute (almost synonymous) § These terms are loosely used as synonyms. § A Field or Instance Variable is generally a private variable on a instance class. It does not mean there is a getter and setter. § Property is a field that you can get or set, typically with a getter or setter § Attribute is a vague term. It refers to anything that describes an object. § Made more confusing in that different languages sometimes use these terms a little differently. Slide

Terminology: Methods Objects have operations which can be invoked § Java calls them methods § Sometimes they are called functions or procedures Methods allow changing or accessing properties/characteristics of the object Methods may have parameters to pass additional information needed to execute. § I may also refer to parameters as arguments You can tell what parameters a method takes by looking at its signature. § I may also refer to signatures as prototypes 15 Slide

7 Data types But slides have much greater detail Slide

Programming Languages Variables Data in a Java program is stored in memory. Variable names represent a location in memory. Variables in Java are sometimes called fields. Variables are created by the programmer who assigns it a programmer-defined identifier. ex: int hours = 40; In this example, the variable hours is created as an integer (more on this later) and assigned the value of 40. Slide

The Eight Primitive Data Types Primitive data types are built into the Java language and are not derived from classes Murach’s Java Programming, C 3 © 2011, Mike Murach & Associates, Inc. Slide

Variable Declarations and Initialization Variable Declarations take the following form: § Data. Type Variable. Name; § byte inches; § short month; § int speed; § long time. Stamp; § float sales. Commission; § double distance; Variable Initialization occurs when the variable is set to its first value Slide

Initialization and Declaration of Variables SYNTAX: How to declare and initialize a variable in two statements SYNTAX: How to declare and initialize a variable in one statement Murach’s Java Programming, C 3 © 2011, Mike Murach & Associates, Inc. Slide

Integer Data Types byte, short, int, and long are all integer data types. They can hold whole numbers such as 5, 10, 23, 89, etc. Integer data types cannot hold numbers that have a decimal point in them. Integers embedded into Java source code are called integer literals. Examples of integer values: § 24, -46, 0, etc. Slide

Example: Integer Data Types // This program has variables of several of the integer types. public class Integer. Variables { public static void main(String[] args) { int checking; // Declare an int variable named checking. byte miles; // Declare a byte variable named miles. short minutes; // Declare a short variable named minutes. long days; // Declare a long variable named days. checking = -20; miles = 105; minutes = 120; days = 185000; System. out. print("We have made a journey of " + miles); System. out. println(" miles. "); System. out. println("It took us " + minutes + " minutes. "); System. out. println("Our account balance is $" + checking); System. out. print("About " + days + " days ago Columbus "); System. out. println("stood on this spot. "); } } Slide

Real Number Data Types Data types that allow fractional values are called floating-point numbers. § 1. 7 and -45. 316 are floating-point numbers. In Java there are two data types that can represent floating-point numbers. § float - also called single precision § (7 decimal points) § double - also called double precision § (15 decimal points) § Real numbers: 43. 56, 3. 7 e 10, -3. 0, -7. 192 e-19 Slide

Real Number Literals (1) When floating-point numbers are embedded into Java source code they are called real number literals. The default data type for floating-point literals is double. § 29. 75, 1. 76, and 31. 51 are double data types. Java is a strongly-typed language. § Every variable must have a data type A double value is not compatible with a float variable because of its size and precision. § float number; § number = 23. 5; // Error! A double can be forced into a float by appending the letter F or f to the literal. § float number; § number = 23. 5 F; // This will work. Slide

Floating Point Literals (2) Literals cannot contain embedded currency symbols or commas. § gross. Pay = $1, 257. 00; // ERROR! § gross. Pay = 1257. 00; // Correct. Real number literals can be represented in scientific notation. § 47, 281. 97 == 4. 728197 x 104. Java uses E notation to represent values in scientific notation. § 4. 728197 X 104 == 4. 728197 E 4. Slide

Example: Double Data Type // This program demonstrates the double data type. public class Sale { public static void main(String[] args) { double price, tax, total; } } price = 29. 75; tax = 1. 76; total = 31. 51; System. out. println("The price of the item " + "is " + price); System. out. println("The tax is " + tax); System. out. println("The total is " + total); Slide

Scientific and E Notation for Doubles Decimal Notation // This program uses E notation. Scientific Notation E Notation 247. 91 2. 4791 x 102 2. 4791 E 2 0. 00072 7. 2 x 10 -4 7. 2 E-4 2. 9 x 106 2. 9 E 6 2, 900, 000 public class Sun. Facts { public static void main(String[] args) { double distance, mass; distance = 1. 495979 E 11; mass = 1. 989 E 30; System. out. print("The Sun is " + distance); System. out. println(" meters away. "); System. out. print("The Sun's mass is " + mass); System. out. println(" kilograms. "); } } Slide

The boolean Data Type The Java boolean data type can have two possible values. § true § false The value of a boolean variable may only be copied into a boolean variable. // A program for demonstrating // boolean variables public class True. False { public static void main(String[] args) { boolean bool; bool = true; System. out. println(bool); bool = false; System. out. println(bool); } } Slide

The char Data Type The Java char data type provides access to single characters. char literals are enclosed in single quote marks. § 'a', 'Z', 'n', '1‘, 'u 00 F 6' (ö) // This program demonstrates the // char data type. public class Letters { public static void main(String[] args) { char letter; Don’t confuse char literals with string literals. letter = 'A'; System. out. println(letter); letter = 'B'; System. out. println(letter); § char literals are enclosed in single quotes. § String literals are enclosed in double quotes. } } Slide

Unicode Internally, characters are stored as numbers. Character data in Java is stored as Unicode characters. The Unicode character set can consist of 65536 (216) individual characters. This means that each character takes up 2 bytes in memory. // This program demonstrates the // close relationship between // characters and integers. public class Letters 2 { public static void main(String[] args) { char letter; letter = 65; System. out. println(letter); letter = 66; System. out. println(letter); The first 256 characters in the Unicode character set are compatible with the ASCII* character set. *American Standard Code for Information Interchange } } Slide

Unicode A B 00 65 00 66 0 0 0 0 0 1 0 0 1 0 Slide

Unicode A Characters are stored in memory as binary numbers. B 00 65 00 66 0 0 0 0 0 1 0 0 1 0 Slide

Unicode A The binary numbers represent these decimal values. B 00 65 00 66 0 0 0 0 0 1 0 0 1 0 Slide

Unicode A 00 65 B The decimal values represent these characters. 0 0 0 0 0 1 00 66 0 0 0 0 0 1 0 Slide

Binary Code Binary Number System: 1 s & 0 s Number of Bits (switches) Possibilities Power of Two 1 2 20 2 4 21 3 8 22 4 16 23 5 32 24 6 64 25 7 128 26 8 256 27 Bit –smallest unit of digital information 8 bits = 1 byte Binary code has two possible states: on/off, 1/0, yes/no With 8 bits there are 256 different possible combinations Copyright © 2015 Pearson Education, Inc. Slide

How to Counting in base 10 The odometer model 0 0 0 0 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 5 0 0 0 0 6 0 0 0 0 7 0 0 0 0 8 0 0 0 0 9 0 0 0 1 0 0 0 0 1 1 § Think of odometers in old cars or gas station pumps 9 is the last digit. The wheel flips back to 0, and the second wheel starts to turn Slide

Bases Our numbers (base 10) Counting in Octal § 10 digits: 0 through 9 Binary (base 2) § 2 digits: 0 through 1 § Usage: How computers store data Octal (base 8) § 8 digits: 0 through 7 § Usage: UNIX/Linux file permissions Hexadecimal (base 16) 0 0 0 0 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 5 0 0 0 0 6 0 0 0 0 7 0 0 0 1 0 0 0 0 1 1 § 16 digits: 0 through 9, A, B, C, D, E, F 7 is the last digit. The wheel flips back § Usage: Color codes to 0, and the second wheel starts to turn © 2006 Pearson Addison-Wesley. All rights reserved Slide

Base Conversions (1) Remember "places"? 1 0 9 2 0 the "one's" place (100) We have 2 ones 2 the "ten's" place (101) We have 9 tens 90 the "hundred's" place (102) We have 0 hundreds 0 the "thousand's" place (103) We have 1 thousand 1000 1092 Binary 1 base 10 1 1 What does the binary number 1011 translate to in base 10? the "one's" place (20) We have 1 ones 1 the "two's" place (21) We have 1 two 2 the "four's" place (22) We have 0 fours 0 the "eight's" place (23) We have 1 eight 8 Slide

Base Conversions 1 4 0 (2) 2 the "one's" place (80) the "eight's" place (81) OCTAL the "sixty-four's" place (82) the "512's" place (83) 0 0 1 D the "one's" place (160) the "sixteen's" place (161) HEXADECIMAL the "256's" place (162) the "4096's" place (163) Slide

Hexadecimal and Octal in Java public class Octal. And. Hex { public static void main(String args[]) { int octal. Eleven = 013; // Note leading zero int hex. Eleven = 0 x. B; // Note leading 0 x System. out. println("Octal: " + (octal. Eleven + 3)); System. out. println(" Hex: " + (hex. Eleven + 3)); } } Octal: 14 Hex: 14 Slide

Object Interaction Slide

Building a House (Answer these questions using Blue. J) What is a class? What is an object? What is an instance of a class? What are parameters to the method call? What are the fields in a class? What are the fields in an object? What is the state of an object? (use the object inspector) What are the attributes in an object’s fields? Why are parameters specified differently for methods change. Size and change. Color? What are the data types of the various parameters? 42 Slide

Making a House (Exercise 1. 9) We had to create all the objects manually. What are the next steps? § Change color of roof object to green § Move roof horizontally § Move roof vertically § Create new Circle called "sun" … Slide

o m e d The house project Slide

o m e d Additional Blue. J concepts Project Compile Object Bench 45 Slide

Source code 12 Each class has source code (Java code) associated with it that defines its details (properties and methods). Examine code of class Circle (double click) Examine declaration of the class fields: § private int diameter; § private int x. Position; § private int y. Position; § private String color; § private boolean is. Visible; Examine the class headers Slide

Object Interaction Compare figures project to house project 12 public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; … public void draw() { wall = new Square(); wall. move. Horizontal(-140); wall. move. Vertical(20); wall. change. Size(120); wall. make. Visible(); window = new Square(); window. change. Color("black"); window. move. Horizontal(-120); window. move. Vertical(40); window. change. Size(40); window. make. Visible(); Slide

Examining a class New class Picture § Attributes (data) § Methods (actions) Here are some of the actions we did manually Why don't we have to change the color of wall? (1) 12 -13 public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; … public void draw() { wall = new Square(); wall. move. Horizontal(-140); wall. move. Vertical(20); wall. change. Size(120); wall. make. Visible(); window = new Square(); window. change. Color("black"); window. move. Horizontal(-120); window. move. Vertical(40); window. change. Size(40); window. make. Visible(); Slide

Examining a class public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; … public void draw() { wall = new Square(); wall. move. Horizontal(-140); wall. move. Vertical(20); wall. change. Size(120); wall. make. Visible(); (2) 12 -13 Class Header § Gives a name to the class and defines its access Class Body § The body of a class definition. The body groups the definitions of a class's members (i. e. , fields and methods) window = new Square(); window. change. Color("black"); window. move. Horizontal(-120); window. move. Vertical(40); window. change. Size(40); window. make. Visible(); Slide

Examining a class public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; … public void draw() { wall = new Square(); wall. move. Horizontal(-140); wall. move. Vertical(20); wall. change. Size(120); wall. make. Visible(); window = new Square(); window. change. Color("black"); window. move. Horizontal(-120); window. move. Vertical(40); window. change. Size(40); window. make. Visible(); (3) 12 -13 "wall" is a property / attribute of Picture. So is "window" Each are instances of class Square. "draw" is a method of picture. "move. Vertical" is a method of the instance "wall" So is "make. Visible" Note how these instance methods are called (invoked). Parameters to the methods are enclosed in parentheses Note that the Class Square is the "blueprint" which means that all square instances will have the same methods. Slide

Examining a class public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; … public void draw() { wall = new Square(); wall. move. Horizontal(-140); wall. move. Vertical(20); wall. change. Size(120); wall. make. Visible(); window = new Square(); window. change. Color("black"); window. move. Horizontal(-120); window. move. Vertical(40); window. change. Size(40); window. make. Visible(); (4) 14 Return value § The value returned from a method All the methods in the house project are defined as void. This means they do not return a value; but … … methods may return a result via a return value. Such methods have a non-void return type. More on this in the next chapter. Slide

o m e d The lab-classes project: Return Values 14 /** * The Student class represents a student in a student * administration system. * It holds the student details relevant in our context. * * @author Michael Kalling and David Barnes * @version 2011. 07. 31 */ public class Student {. . . // Return the full name of this student. public String get. Name() { return name; } // Set a new name for this student. public void change. Name(String replacement. Name) { name = replacement. Name; } return value no return value Slide

What Sticks Around? Objects you make and manipulate on the object bench disappear when § You quit from Blue. J § You change the source code Source code sticks around, as long as you save it § Remember if you “save” rather than “save as” you may overwrite the book example files! Slide

Saving work you do on the object bench Sorry you can’t! But you can “record” the things you would do inside a method in the source code § View terminal window § Options: record method calls Slide

Tracing a simple program Slide

Before we start tracing… It is important that we distinguish different types of variables. Slide

Primitive vs. Reference Variables Primitive variables actually contain the value that they have been assigned. int number = 25; The value 25 will be stored in the memory location associated with the variable number. Objects are not stored in variables, however. Objects are referenced by variables. memory location number int 25 Slide

Primitive vs. Reference Variables When a variable references an object, it contains the memory address of the object’s location. Then it is said that the variable references the object. wall: Square private Square wall = new Square(); int 120 x. Position memory location wall size int 170 Square y. Position int 140 color Str "red" is. Visible bool true 2 -58 Slide

Local vs. Instance Variables Instance Variable § A field of a class. Each individual object of a class has its own copy of such a field. public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; . . . Local Variable § A variable defined inside a method body. public static void main (String[] args) {. . . double discount. Percent =. 2; Slide

Tracing local variables method: main Scanner sc a Scanner object subtotal double 500 p ra “sc er p a p ” Slide

Two circle objects: Book notation Slide

Tracing Instance Variables circle_1: Circle diameter int 50 80 int I note the type of each field x. Position int 230 y. Position int 75 Str "blue" is. Visible bool true diameter 30 x. Position int color circle_2: Circle color Str Book Notation: "red" is. Visible bool true Slide

Inspecting my. Picture: Blue. J 64 Slide

Inspecting my. Picture: Blue. J 65 Slide

Inspecting my. Picture: Blue. J 66 Slide

wall: Square My notation size int 120 x. Position int 170 roof: Triangle height my. Picture: Picture wall Square 180 x. Position 330 y. Position window Square window: Square size Str roof Triangle true x. Position int 190 bool true y. Position int 160 Str "yellow" is. Visible int 40 50 color bool int "green" is. Visible int "red" true int 80 color int Str color is. Visible 230 int 140 int width diameter int 60 sun: Circle y. Position bool sun Circle color Str "black" is. Visible bool true Slide

Looking at the Picture Class Names of all of the fields in the class seem to be listed at the top of the code public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; my. Picture: Picture wall Square window Square roof sun Triangle Circle Slide

Looking at the Picture Class wall: Square size int 120 Create a new instance of the Square class called “wall” public void draw() { wall = new Square(); wall. move. Horizontal(-140); wall. move. Vertical(20); wall. change. Size(120); wall. make. Visible(); window = new Square(); window. change. Color("black"); window. move. Horizontal(-120); window. move. Vertical(40); window. change. Size(40); window. make. Visible(); x. Position int 170 y. Position int 140 color Str "red" is. Visible bool true Do the setup for “wall” Setup for all of the fields seems to be inside the draw method Slide

wall: Square size Looking at the Picture Class int 120 x. Position int 170 y. Position Next, create a new instance of the Square class called “window” public void draw() { wall = new Square(); wall. move. Horizontal(-140); wall. move. Vertical(20); wall. change. Size(120); wall. make. Visible(); window = new Square(); window. change. Color("black"); window. move. Horizontal(-120); window. move. Vertical(40); window. change. Size(40); window. make. Visible(); int 140 Str color "red" is. Visible bool true Do the setup for “window” window: Square size int 40 x. Position int 190 y. Position int 160 color Str "black" is. Visible bool true Slide

Naming Java Requirements: § Identifiers must consists of letters, digits, underscore ( _ ) or dollar sign ($) § Identifiers must start with a letter - cannot start with digit Java Conventions (and my requirements): § Class names start with capital letter - Use Pascal. Casing § Method / variable names should be clear and descriptive – Use camel. Casing § Avoid one letter and meaningless identifier names 71 Slide

Looking Closer at the Code: Method Signatures 6 -7 General Pattern Seems to Be: public void method. Name(sometimes parameters here) Examples from Triangle classes in figures example : public void make. Visible() public void move. Right() public void move. Horizontal(int distance) public void change. Size(int new. Height, int new. Width) public void change. Color(String new. Color) Slide

Demo Open Lab-classes project Make a new student § Hey – this method takes parameters! Try the get. Name method § Returns a value Change the student’s name & get. Name again Look at Student Class Methods § Can we tell which return values? Slide

Method Signatures 6 -7 General Pattern: public return. Type method. Name(sometimes parameters here) Examples from Triangle class in figures example : public void make. Visible() public void move. Horizontal(int distance) public void change. Size(int new. Height, int new. Width) Void means: “This space intentionally left blank” 74 Slide

Method Signatures 6 -7 General Pattern: public return. Type method. Name(sometimes parameters here) Examples from Triangle class in figures example : public void make. Visible() public void move. Horizontal(int distance) public void change. Size(int new. Height, int new. Width) Examples from Student class in figures example : public String get. Name() public int get. Credits() public String get. Student. ID() public void add. Credits(int additional. Points) public void change. Name(String replacement. Name) Slide

Return values 14 public return. Type method. Name(sometimes parameters here) return. Type can be: § primitive data type (like int or float or double or char) § class (like Circle or Student) or § void (no return value) 76 Slide

Parameters public return. Type method. Name(sometimes parameters here) parameters are: § Separated by commas Each parameter consists of § <parameter data type> &<parameter name> <parameter data type> § Can be a primitive data type or a class <parameter name> § The alphanumeric name of the parameter Slide

IOOP Glossary Terms to Know Terms to know for tests/quizzes (see class web site) argument binary boolean class body class header data type decimal floating-point number hexadecimal instance variable integer local variable member method body method header method result method signature octal parameter primitive type return statement return type return value real number Non-glossary terms to know initialization Note: declaration property the glossary definitions are complete ones, based on a full understanding of the material which we might not yet have. However, there are elements of the definitions that you should be able to grasp from this material. Slide
- Slides: 77