Chapter 2 – Using Objects Chapter Goals To learn about variables To understand the concepts of classes and objects To be able to call methods To.
Download ReportTranscript Chapter 2 – Using Objects Chapter Goals To learn about variables To understand the concepts of classes and objects To be able to call methods To.
Chapter 2 – Using Objects
Chapter Goals
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 in java) “Hello, 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
4 properties to a variable 1.
A type 2.
A name (identifier) 3.
Memory location 4.
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?
Data Types
Primitive: (language defined) Numeric Non-numeric Reference: (programmer defined) Object stores several variables that collectively represent a single entity
Numerical data types
There are six
numerical data types
Two sets Integers – byte, short, int, long, 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’s the tradeoff to higher precision?
Integers
byte
1 byte of information (8 bits) Range from -128 to 127
short
2 bytes Range from -32768 to 32767
int
4 bytes Range from -2147483648 to 2147483647
Integers
long
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 Flexible Efficient
Reals
double vs. float
double really stands for double float – twice the memory Float – up to 10 38 or 7 decimal digits Double – up to 10 308 or 15 decimal digits Floating point representation Similar to scientific notation Usually use double, more possible values
Numbers
Do not use commas 13,000
13000
Can represent exponents 1.3 x 10 -4
1.3E-4
Why have integers?
Why can’t we just represent all integers as floating-point?
Memory Faster Rounding
Identifiers
Identifier: name of a variable, method, or class Must follow Naming Standards – rules for creating identifiers Should follow Naming conventions – make identifiers useful and readable
5.
3.
4.
2.
1.
Naming Standards (must be)
Use only: a) b) c) letters digits _ 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( )
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 Die bike; 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” or “x gets y”
Assignment statement
x = 20; a = 3.5;
z = x; y = 0.12;
Don’t confuse with mathematical statement
x + y = a + b; // Not valid 4+10 = x; // Not valid
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
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;
int memory location
Initialization
int total = 1; total
name (identifier)
Initialization
int total = 1 ; 1 total
value
total = 3 ;
Assignment
total
Uninitialized Variables
Error:
int 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)
int x, y; x = 123; y = x + x; System.out.print(“Hello, Dr. Caffeine.”); System.out.print(“ x = “); System.out.print( x ); System.out.print(“ x + x = “); System.out.print( y ); System.out.print( “ THE END “);
Example
Mismatches
You will get an error if the value does not match the variable type String st =13; int x = “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
Example
One object given to us is System.out, which is connected to the console We can call the method println(), which manipulates the object to output a message to the screen
Methods
Method: Sequence of instructions that accesses the data of an object You manipulate objects by calling its methods
Class
Class: Blueprint for objects with the same behavior Class determines legal methods
String greeting = "Hello"; greeting.println() // Error 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, Grade, Car, MP3Player, Phone, Course, Semester, etc…
Components of an object
Objects contain Data members – information the object needs to store Methods – things the object can do
Color myFavColor Color
How do we represent an object?
red green blue
255 153 51
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)
3.
Draw a circle around these two lists.
4.
Draw an arrow from the inside of the rectangle above to your circled list.
You've just defined and created your first Object!
We can make any object we need for our programs in much the same way.
2.4 Method Parameters
Parameter (explicit parameter): Input to a method. Not all methods have explicit parameters.
System.out.println( greeting ) greeting.length() // has no explicit parameter
Implicit parameter: The object on which a method is invoked
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 value stored in n
Passing Return Values
You can also use the return value as a parameter of another method:
method composition System.out.println(greeting.length());
Note: Not all methods return values. Example: println() These are return type void
String Methods
Concatenation
quote = “Go Badgers” + “!”; Length
int quoteLength = quote.length(); Index of
int find = quote.indexOf(“Badgers”); find = quote.indexOf(“Buckeyes”); UpperCase Converstion
String name = “apple”; name.toUpperCase(); //
”APPLE”
More complex method calls
replace method carries out a search-and replace operation
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)
Rectangle
The
Rectangle
class will provide an example Does not visually create a rectangle, rather describes it numerically (x,y) coordinate of upper-left corner Width Height
Creating Objects
Primitives do not need to be constructed Just declare (int x;) and use (x = 4;) 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 Constructs the memory for the object
new Rectangle(5, 10, 20, 30)
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
new Rectangle(5, 10, 20, 30)
new
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
called of the specified class should be 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);
Syntax 2.3: Object Construction
new
ClassName
(
parameters
) Example:
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
Constructors
Most classes let you construct the object in different ways Default – gives default values (all 0) 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) is an accessor
Mutator
– a method whose purpose is to modify the state of an object
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’s a waste of time and space to include them automatically in all programs
Import
Solution:
Import
packages containing the classes you need manually Example:
Rectangle
needs to be imported
Package
– collection of classes with a related purpose
java.awt
contains
Rectangle
Syntax 2.4 : Importing a Class from a Package
import packageName.ClassName; Example: import java.awt.Rectangle; Purpose:
To import a class from a package for use in a program.
Advantages of Packages
Very useful, do not have to rewrite something that has already been done Can create your own packages, use in other programs without having to cut and paste code
Advantages of Import
Can use in code without importing
javax.swing.JFrame newFrame ; java.awt.Rectangle box;
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
java.lang
There is an exception You do not need to import
java.lang
Automatically included
System, String, Math
, etc
import java.awt.Rectangle; public class MoveTester { public static void main(String[] args) { Rectangle box = new Rectangle(5,10,20,30); // Move the rectangle box.translate(15, 25); } } // Print info about the moved rectangle System.out.println(“Top-left corner now:"); System.out.println(box.getX()); System.out.println(box.getY());
Output
Top-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)
Object References
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
Primitive in memory
Reference in memory
Why is this important?
Copying of variables shows difference Example:
int luckyNumber = 13; int luckyNumber2 = luckyNumber; luckyNumber2 = 12;
Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = box; box2.translate(15, 25);
2.9 API Documentation
API: Application Programming Interface Lists classes and methods in the Java library 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
API
Lists purpose of class at the top Summary of constructors and methods Lesson – don’t memorize specialized classes, use documentation Google: java 1.5