Chapter 2 Using Objects

Chapter Goals Chapter 2 – Using Objects To learn about variables To understand the concepts of classes and objects To be able to call methods To be ...
Author: Grant Bailey
2 downloads 0 Views 224KB Size
Chapter Goals

Chapter 2 – Using Objects

To learn about variables To understand the concepts of classes and objects To be able to call methods To be able to browse the API documentation To realize the difference between objects and object references

2.1 Types and Variables Every value has a type A type describes what category a certain piece of information falls in (number, string, bank account, etc) 13 is an integer (int (int in java) “Hello, World” World” is a String 13.3 is a real (double in java)

How do we store a value for later use?

2.1 Variables Math: A letter that represents an unknown value. y = 3x + z

CS Programming: Named space (in memory) that stores a value. Like mathematics, we can use variables to represent unknown or changing values.

Variables

Data Types

4 properties to a variable 1. 2. 3. 4.

A type A name (identifier) Memory location A value

2 Decisions for declaring a variable What type should the variable be? What am I going to use the variable for?

What name should the variable have?

Primitive: (language defined) Numeric NonNon-numeric

Reference: (programmer defined) Object stores several variables that collectively represent a single entity

1

Numerical data types There are six numerical data types Two sets Integers – byte, short, int, int, long, Reals/Floating Reals/Floating Point – float, double

Difference is the range of possible values Higher precision means larger range of values Can be more exact with the value

What’ What’s the tradeoff to higher precision?

long

Integers

8 bytes Range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Which one should we use? Why not always short? Why not always use long?

Settle on int

short 2 bytes Range from -32768 to 32767

int 4 bytes Range from -2147483648 to 2147483647

Reals

double vs. float

double really stands for double float – twice the memory Float – up to 1038 or 7 decimal digits Double – up to 10308 or 15 decimal digits

Floating point representation Usually use double, more possible values

Numbers Do not use commas 13000

Can represent exponents 1.3 x 10-4

1 byte of information (8 bits) Range from -128 to 127

Similar to scientific notation

Flexible Efficient

13,000

Integers

byte

1.3E1.3E-4

Why have integers? Why can’ can’t we just represent all integers as floatingfloating-point? Memory Faster Rounding

2

Identifiers

Naming Standards (must be) 1.

Identifier: name of a variable, method, or class Must follow Naming Standards – rules for creating identifiers

a) letters b) digits c) _ 2. 3. 4.

Should follow Naming conventions – make identifiers useful and readable

Use only:

5.

Cannot start with a digit Cannot be a reserved word Case sensitive No spaces, punctuation

Naming Conventions (should be) Useful to follow, make program easier to read Variables and methods start with lowercase letter. variableName and methodName( methodName( )

Class names should start with an uppercase ClassName

CONSTANTS_ALL_CAPS If two word joined, the first letter of the second word should be capitalized

Declaration Declaration: ; ;

Examples: Bicycle bike; Die die1, die2; PopCan can1, can2, can3; int height, width;

Assignment Assignment variableName = value; Example: luckyNumber = 12; // luckyNumber must be able // to be set to 12 Purpose: To assign a new value to a previously defined variable. Assigns the value of the right side of the = to the variable on the left side You can think of x = y as “x becomes y” y” or “x gets y” y”

Assignment statement x = 20; z = x;

a = 3.5;

y = 0.12;

Don’ Don’t confuse with mathematical statement x + y = a + b; // Not valid 4+10 = x; // Not valid

3

The first time we assign a value to a new variable, it is called initialization If we want, we can declare and initialize a variable in one statement = int size = 10;

Before using a variable, we must declare it and initialize it

Assignment = operator is an action to assign (replace) the a value to a variable Not used as a statement about equality Used to change the value of a variable int luckyNumber = 13; luckyNumber = 12;

Initialization int total = 1;

Initialization int total = 1;

int memory location total

Initialization int total = 1;

name (identifier)

Assignment total = 3;

1 total

value

3 1 total

4

Uninitialized Variables Error: int luckyNumber; luckyNumber; System.out.println(luckyNumber); System.out.println(luckyNumber); // ERROR - uninitialized variable

Arithmetic The data types discussed so far do not have methods But we can do arithmetic operations +-*/ Follow the rules of mathematics, including Order of Operations (with parentheses) 10 + 2 10 – n 10 * n 2 / (1 – n)

Example int x, y; x = 123; y = x + x; System.out.print(“ System.out.print(“Hello, Hello, Dr. Caffeine.” Caffeine.”); System.out.print( System.out.print(“ x = “); System.out.print( System.out.print( x ); System.out.print( System.out.print(“ x + x = “); System.out.print( System.out.print( y ); System.out.print( System.out.print( “ THE END “);

Mismatches You will get an error if the value does not match the variable type String st =13; int x = “Go” Go”;

The name of the variable is the identifier Choose something useful (if storing a height, call the variable height, not h)

2.3 Objects, Classes, and Methods The numbers we learned are primitive dataypes – represented directly in memory No methods

Object – entity that you can manipulate in a program Manipulated via methods – predefined functions that we can call

5

Example One object given to us is System.out, System.out, which is connected to the console We can call the method println(), println(), which manipulates the object to output a message to the screen

Class

Methods Method: Sequence of instructions that accesses the data of an object

Class: Blueprint for objects with the same behavior

You manipulate objects by calling its methods

Class determines legal methods String greeting = "Hello"; greeting.println() greeting.println() // Error greeting.length() greeting.length() // OK

Public Interface: Specifies what you can do with the objects of a class

Reference Data (Objects) Programmers can define their own object types and create instances of those types for use in their programs. Book, Student, BankAccount, BankAccount, Grade, Car, MP3Player, Phone, Course, Semester, etc… etc…

Components of an object Objects contain

Color myFavColor

Data members – information the object needs to store Methods – things the object can do

How do we represent an object?

Color red green blue

6

Concrete Object Think of an object in your backpack, purse, pocket? 1.

Write down the type of your object. Book

2.

Give your object a variable name and write it down next to the type. cs302Textbook

3.

Draw a rectangle next to the name

Virtual Object 1. Write a list of nouns or adjectives that describe your object? title = "Java Concepts"

2. Write a list of things that your object can do? or things that can be done to it? openToPage(x) openToPage(x)

3. Draw a circle around these two lists. 4. Draw an arrow from the inside of the rectangle above to your circled list.

2.4 Method Parameters

You' ve just defined and created your first Object! We can make any object we need for our programs in much the same way.

Parameter (explicit parameter): Input to a method. Not all methods have explicit parameters. System.out.println(greeting ) System.out.println(greeting) greeting.length() greeting.length() // has no explicit parameter

Implicit parameter: The object on which a method is invoked System.out.println(greeting ) System.out.println(greeting)

Return Values Return value: A result that the method has computed for use by the code that called it int n = greeting.length();//return greeting.length();//return value stored in n

7

Passing Return Values You can also use the return value as a parameter of another method: method composition System.out.println(greeting.length()); System.out.println(greeting.length());

Note: Not all methods return values. Example: println() println() These are return type void

String Methods Concatenation

quote = “Go Badgers” Badgers” + “!”;

Length

int quoteLength = quote.length(); quote.length();

Index of

int find = quote.indexOf(“ quote.indexOf(“Badgers” Badgers”); find = quote.indexOf(“ quote.indexOf(“Buckeyes” Buckeyes”);

UpperCase Converstion

String name = “apple” apple”; name.toUpperCase(); name.toUpperCase(); // ”APPLE” APPLE”

More complex method calls replace method carries out a searchsearch-andandreplace operation river.replace("issipp", river.replace("issipp", "our"); // constructs a new string ("Missouri")

What is the implicit parameter? What is/are the explicit parameters? a return value: the string "Missouri"

Method definitions

What determines the number/type of parameters? The return value? When a method is defined in a class, the programmer must specify Example – String method definitions public int length() public void replace (String target, String replacement)

8

Rectangle The Rectangle class will provide an example

Creating Objects Primitives do not need to be constructed Just declare (int (int x;) and use (x = 4;)

Does not visually create a rectangle, rather describes it numerically (x,y) x,y) coordinate of upperupper-left corner Width Height

Objects cannot be used after declaring Must also CREATE the object

Creating objects Declaring objects Tells what template to associate with the variable Rectangle box

Creating the object

What’ What’s the difference between declare and create? Declare gives space in memory to hold (address) Create actually creates object, now pointed to by memory

Constructs the memory for the object new Rectangle(5, 10, 20, 30)

new Rectangle(5, 10, 20, 30)

specifies that an object is to be created Rectangle is the class (template) for the new object () states that a special method called the constructor of the specified class should be called new

The parameters are used to initialize the data

Detail: The new operator makes a Rectangle object It uses the parameters (in this case, 5, 10, 20, and 30) to initialize the data of the object It returns the object

Usually the output of the new operator is stored in a variable Rectangle box = new Rectangle(5, 10, 20, 30);

9

Syntax 2.3: Object Construction new ClassName( ClassName(parameters) parameters) Example:

Constructors Most classes let you construct the object in different ways Default – gives default values (all 0)

new Rectangle(5, 10, 20, 30) new Rectangle()

Purpose: To construct a new object, initialize it with the construction parameters, and return a reference to the constructed

box = new Rectangle()

Constructors can only be called when using the new operator

2.7 Accessors and Mutators Accessor – a method that access an object and returns some information about it without changing the object in anyway What String method(s) method(s) is an accessor

Mutator – a method whose purpose is to modify the state of an object

Import Solution: Import packages containing the classes you need manually Example: Rectangle needs to be imported

Import packages Remember: Java has a rich array of predefined classes you can use You only need to use a handful of all of them, so it’ it’s a waste of time and space to include them automatically in all programs

Syntax 2.4 : Importing a Class from a Package import packageName. packageName.ClassName; ClassName;

Example: import java.awt.Rectangle; java.awt.Rectangle;

Package – collection of classes with a related purpose java.awt contains Rectangle

Purpose: To import a class from a package for use in a program.

10

Advantages of Packages

Advantages of Import

Very useful, do not have to rewrite something that has already been done

Can use in code without importing javax.swing.JFrame newFrame ; java.awt.Rectangle box;

Can create your own packages, use in other programs without having to cut and paste code

java.lang There is an exception

This is the fully qualified name for a class Pain in the rear to use every time though Just import the class at the beginning of code

import java.awt.Rectangle; java.awt.Rectangle; public class MoveTester { public static void main(String[] main(String[] args) args) { Rectangle box = new Rectangle(5,10,20,30);

You do not need to import java.lang

// Move the rectangle box.translate(15, 25);

Automatically included System, String, Math, etc

// Print info about the moved rectangle System.out.println(“ System.out.println(“TopTop-left corner now:"); System.out.println(box.getX()); System.out.println(box.getX()); System.out.println(box.getY()); System.out.println(box.getY()); } }

Output TopTop-left corner now: 20 35

2.10 Object References As stated earlier, objects are reference variables Any variable with a class type

The variable refers to the memory location of the object, not the object itself (importance revealed later on)

11

Object References

Primitive in memory

The new operator returns a reference to a new object Rectangle box = new Rectangle();

Multiple object variables can refer to the same object Rectangle box = new Rectangle(5,10,20,30); Rectangle box2 = box; box2.translate(15, 25);

Primitive type variables

object variables

Reference in memory

Why is this important? Copying of variables shows difference Example:

Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = box; box2.translate(15, 25);

int luckyNumber = 13; int luckyNumber2 = luckyNumber; luckyNumber; luckyNumber2 = 12;

12

2.9 API Documentation

API

API: Application Programming Interface

Lists purpose of class at the top

Lists classes and methods in the Java library

Summary of constructors and methods

http://java.sun.com/j2se/1.5/docs/api/index.html All System classes are in the documentation

Thousands! Only a few will be useful in this course

Lesson – don’ don’t memorize specialized classes, use documentation Google: java 1.5 Example: java 1.5 String

13