Chapter 2 Using Objects Overview This chapter touches
Chapter 2 – Using Objects
Overview This chapter touches briefly on topics we will discuss as the course progresses Objects – main point of course n n First, learn about objects How to use objects we already know about Create objects Design classes to complete a task requirement
Basic Computer Program What is the basis of computing? Mathematics n Program has three generic steps 1. 2. 3. Get input data Perform computation on that data Output the results of that computation For example, perhaps we want to be able to compute the sum of two terms x and y. How do we do that?
Types and Variables Every value (piece of data) has a type n n 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? n Answer: variables
Variables In math, a variable represents an unknown value. y = 3 x + z In computer science, a variable is a named space (in memory) that stores a value. Like mathematics, a variable can store any value in a given range.
Variable Declaration type. Name variable. Name = value; or type. Name variable. Name; Example: n String greeting = "Hello, Bob!"; Purpose: n To define a new variable of a particular type and optionally supply an initial value
Variables have four key ingredients: 1. 2. 3. 4. The type of data stored A name (also called an identifier) A memory location A value To declare a variable, you need to decide n n What type you should use for the variable (ie what kind of data am I going to store) What name you should give to the variable
Data Values Examples of values: n n All of these values have an 3. 141592 associated type 27 "The Grapes of Wrath" Color. ORANGE All of the above are literals You cannot store values in variables of the wrong type…
Data Types Color my. Fav. Color Primitive: (language defined) n n Numeric (int, double) Non-numeric (boolean) Reference: (programmer defined) n Color red 255 green 153 Object stores several variables that collectively represent a single entity blue 51
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
Naming Standards 1. Use only: a) b) c) d) 2. 3. 4. 5. letters digits _ $ Start with a letter Cannot be a reserved word Case sensitive No spaces, punctuation
Naming Conventions Useful to follow, make program easier to read Variables and methods start with lowercase letter n variable. Name and method. Name( ) Class names should start with an uppercase letter n Class. Name CONSTANTS_ALL_CAPS If two words are joined, the first letter of the second word should be capitalized (camel case)
Memory Location When you declare a variable, the computer will you a memory location for storing the value of that variable When dealing with objects, you need to use new to create space for the object (we’ll cover this later)
Declaration Examples Declaration: <type> <identifiers>; Examples: n n n int month, day, year; String last. Name, first. Name; double account. Balance;
Assignment variable. Name = value; Example: n lucky. Number = 12; Purpose: n To assign a new value to a previously defined variable.
Assignment statement n x = 20; a = 3. 5; y = 0. 12 f; Don’t confuse with mathematical statement x + y = a + b; 4+10 = x; // Not valid Can initialize value during declaration n int x = 20;
IMPORTANT Before using a variable, you must declare it and initialize it
Assignment = operator is an action to assign (replace) the a value to a variable Think about this as ← Not used as a statement about equality Used to change the value of a variable int lucky. Number = 13; lucky. Number = 12;
Initialization int total = 1; int memory location
Initialization int total = 1; total name (identifier)
Initialization int total = 1; 1 total value
Assignment total = 3; 3 1 total
Uninitialized Variables The following code generates an error: int lucky. Number; System. out. println(lucky. Number); // ERROR - uninitialized variable
Questions How do you change the value of the greeting variable to "Hello, Nina!"? Is 12 = x a valid Java statement? How about 12 = x; ?
Numerical Data Types There are six numerical data types Two sets n n Integers – byte, short, int, long Reals/Floating Point – float, double Range vs. Precision What’s the tradeoff with higher precision?
byte n n Integers 1 byte of information (8 bits) Range from -128 to 127 short n n 2 bytes Range from -32768 to 32767 int n n 4 bytes Range from -2147483648 to 2147483647
long n Integers 8 bytes Which one should we use? n n Why not always short? Why not always use long? Settle on int n n Flexible Efficient
Reals double vs. float n double really stands for double float – twice the memory Floating point representation n Similar to scientific notation Default to double, more possible values
Numbers Do not use commas n 13, 000 13000 Can represent exponents n 1. 3 x 10 -4 1. 3 E-4
Why have integers? Integers are a subset of the reals… Why can’t we just represent all integers as floating-point? n n n Memory Speed Rounding
Arithmetic The data types discussed so far do not have methods But we can do arithmetic operations - + * / n n n Follow the rules of mathematics, including order of operations 10 + 2 10 – n 10 * n 2 / (1 – n)
Incorrect Initializations You will get an syntax error if the value does not match the variable type n n String st = 13; int x = “Go”; The name of the variable is the identifier n Choose something useful (if storing a height, call the variable height, not h)
Strings String – sequence (i. e. string) of characters, surrounded by quotes n Example: String str = “This is a string. ”;
String Methods Concatenation n quote = “Go Badgers” + “!”; Length n int quote. Length = quote. length(); Index of n n int find = quote. index. Of(“Badgers”); find = quote. index. Of(“Buckeyes”); Capitalization n n String name = “betsy”; name. to. Upper. Case(); // ”BETSY”
Objects, Classes, and Methods The numbers we learned are primitive datatypes – represented directly in memory n 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 uses this object to output a message to the screen
Methods Method: Sequence of instructions that uses the data of an object You manipulate an object by calling its methods
Objects So far we’ve seen two objects n n System. out “Hello, World!” These objects are clearly not the same type of object n n System. out – Print. Stream “Hello, World!” – String
Class: Template for objects with the same behavior (blueprint) Class determines legal methods String greeting = "Hello"; greeting. println() // Error int 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. n Book, Student, Bank. Account, Grade, Car, MP 3 Player, Phone, Course, Semester, etc…
Example Think about a noun, for example a book n n What data do we care about? What actions would we like to be able to use? These are the decisions involved in designing a class
Example Given a class, for example Book, how do we create individual book objects?
Constructing Objects Java already has lots of cool objects we can use n n n System. out System. in String Not exhaustive Java easily allows you to construct new objects
Rectangle Does not visually create a rectangle, rather describes it numerically n n n (x, y) coordinate of upper-left corner Width Height
Creating Objects Primitives do not need to be constructed n Just declare (int x; ) and use (x = 4; ) Objects cannot be used after declaring n Must also CREATE the object
Creating objects Declaring objects n n Tells what template to associate with the variable Rectangle box Creating the object n Constructs the memory for the object n new Rectangle(5, 10, 20, 30)
Creating Objects What’s the difference between declare and create? n n Declare gives space in memory to hold (address) Create actually creates object, now pointed to by memory
Creating Objects new Rectangle(5, 10, 20, 30) n new specifies that an object is to be created n Rectangle is the class (think template) for the new object n () states that a special method called the constructor of the specified class should be called The parameters are used to initialize the data
Creating Objects Detail: n n n 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 n Rectangle box = new Rectangle(5, 10, 20, 30);
Creating Objects new Class. Name(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
Creating Objects Most classes let you construct the object in different ways n Default – gives default values (all 0) box = new Rectangle() Constructors can only be called when using the new operator
Methods Remember that we call methods on an object by: n Object. Name. method. Name(Parameters); For example: n System. out. println(“Hello, world!”);
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() n These are return type void
More complex method calls replace method carries out a search-and- replace operation river. replace("issipp", "our"); // constructs a new string ("Missouri") n n n 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 n n public int length() public void replace (String target, String replacement)
Accessors and Mutators Accessor – a method that access an object and returns some information about it without changing the object in anyway Mutator – a method whose purpose is to modify the state of an object
Examples Accessors n n String – length() Rectangle – get. Width(), get. Height(), get. X(), get. Y() double width = box. get. Width(); Mutators n Rectangle – set. X(int), set. Y(int), set. Height(int), set. Width(int), translate(int, int) box. set. Width(25);
Object References As stated earlier, objects are reference variables n 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 box 2 = box; box 2. 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 lucky. Number = 13; int lucky. Number 2 = lucky. Number; lucky. Number 2 = 12;
Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box 2 = box; box 2. translate(15, 25);
Writing Programs Build on what we already know Steps: n n Import library packages Class declaration Method declaration (for sure main) Method body Declare and initialize variables Declare and create objects Call methods on objects Print output
Importing 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
Importing Packages Solution: Import packages containing the classes you need manually n Example: Rectangle needs to be imported Package – collection of classes with a related purpose n java. awt contains Rectangle
Importing Packages import package. Name. Class. Name; 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 new. Frame ; java. awt. Rectangle box; This is the fully qualified name for a class n n Really tedious Just import the class at the beginning of code instead
java. lang There is an exception to the import rules You do not need to import java. lang n n Automatically included Includes System, String, Math, etc
import java. awt. Rectangle; public class Move. Tester { 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. get. X()); System. out. println(box. get. Y()); } }
Output Top-left corner now: 20 35
API Documentation API: Application Programming Interface Extremely useful Lists classes and methods in the Java library http: //java. sun. com/j 2 se/1. 5/docs/api/index. html All System classes are in the documentation n 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 n Example
- Slides: 82