Java Basic Introduction, Classes and Objects SEEM

Similar documents
Java Basic Introduction, Classes and Objects SEEM

Chapter. Let's explore some other fundamental programming concepts

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Anatomy of a Class Encapsulation Anatomy of a Method

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

2: Basics of Java Programming

Where do objects come from? Good question!

A variable is a name for a location in memory A variable must be declared

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

2 rd class Department of Programming. OOP with Java Programming

Chapter. We've been using predefined classes. Now we will learn to write our own classes to define objects

Chapter 4: Writing Classes

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Designing Classes part 2

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods

Packages & Random and Math Classes

ECE 122 Engineering Problem Solving with Java

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Chapter 2: Data and Expressions

We now start exploring some key elements of the Java programming language and ways of performing I/O

Lecture 3: Variables and assignment

Chapter 2: Data and Expressions

Chapter 1. Introduction

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Chap. 3. Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L,

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

COMP 202 Java in one week

Data Conversion & Scanner Class

Full file at

Using Classes and Objects. Chapter

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

COMP 202 Java in one week

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Using Classes and Objects

Chapter 2: Data and Expressions

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

ECE 122. Engineering Problem Solving with Java

CMPT 125: Lecture 3 Data and Expressions

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Program Elements -- Introduction

ECE 122. Engineering Problem Solving with Java

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Program Fundamentals

writing classes objectives chapter

3. Java - Language Constructs I

COMP 202. Java in one week

Section 2: Introduction to Java. Historical note

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Objects and Classes -- Introduction

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Computational Expression

CSC 1214: Object-Oriented Programming

An overview of Java, Data types and variables

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

objectives chapter Define the difference between primitive data and objects. Declare and use variables. Perform mathematical computations.

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Variables, Constants, and Data Types

CS1007: Object Oriented Design and Programming in Java. Lecture #2 Sept 8 Shlomo Hershkop Announcements

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Formatting Output & Enumerated Types & Wrapper Classes

Assignment 1 due Monday at 11:59pm

Classes and Objects Part 1

Chapter 2. Elementary Programming

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Computer Components. Software{ User Programs. Operating System. Hardware

Lecture Set 2: Starting Java

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Lecture Set 2: Starting Java

Using Java Classes Fall 2018 Margaret Reid-Miller

ECE 122 Engineering Problem Solving with Java

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

ing execution. That way, new results can be computed each time the Class The Scanner

1 Shyam sir JAVA Notes

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Course Outline. Introduction to java

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Computer Components. Software{ User Programs. Operating System. Hardware

Chapter 4 Writing Classes

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

Introduction to Java Applications; Input/Output and Operators

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

CS111: PROGRAMMING LANGUAGE II

Basics of Java Programming

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

UNIT- 3 Introduction to C++

Transcription:

Java Basic Introduction, Classes and Objects SEEM 3460 1

Java A programming language specifies the words and symbols that we can use to write a program A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since SEEM 3460 2

Java Program Structure In the Java programming language: A program is made up of one or more classes A class contains one or more methods A method contains program statements These terms will be explored in detail throughout the course A Java application always contains a method called main SEEM 3460 3

//************************************************ // Lincoln.java // // Demonstrates the basic structure of a Java application. //************************************************ public class Lincoln { //----------------------------------------------------------------- // Prints a presidential quote. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("A quote by Abraham Lincoln:"); } } System.out.println ("Whatever you are, be a good one."); SEEM 3460 4

Java Program Structure // comments about the class public class MyProgram { class header class body } Comments can be placed almost anywhere 5

Java Program Structure // comments about the class public class MyProgram { // comments about the method public static void main (String[] args) { } method body method header } 6

Comments Comments in a program are called inline documentation They should be included to explain the purpose of the program and describe processing steps They do not affect how a program works Java comments can take three forms: // this comment runs to the end of the line /* this comment runs to the terminating symbol, even across line breaks */ /** this is a javadoc comment */ 7

Identifiers Identifiers are the words a programmer uses in a program An identifier can be made up of letters, digits, the underscore character ( _ ), and the dollar sign Identifiers cannot begin with a digit Java is case sensitive - Total, total, and TOTAL are different identifiers By convention, programmers use different case styles for different types of identifiers, such as title case for class names - Lincoln upper case for constants - MAXIMUM 8

Identifiers Sometimes we choose identifiers ourselves when writing a program (such as Lincoln) Sometimes we are using another programmer's code, so we use the identifiers that he or she chose (such as println) Often we use special identifiers called reserved words that already have a predefined meaning in the language A reserved word cannot be used in any other way SEEM 3460 9

10 Reserved Words The Java reserved words: abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while

White Space Spaces, blank lines, and tabs are called white space White space is used to separate words and symbols in a program Extra white space is ignored A valid Java program can be formatted many ways Programs should be formatted to enhance readability, using consistent indentation 11

Problem Solving The key to designing a solution for a problem is to break it down into manageable pieces When writing software, we design separate pieces that are responsible for certain parts of the solution An object-oriented approach lends itself to this kind of solution decomposition We will dissect our solutions into pieces called objects and classes SEEM 3460 12

Object-Oriented Programming Java is an object-oriented programming language As the term implies, an object is a fundamental entity in a Java program Objects can be used effectively to represent real-world entities For instance, an object might represent a particular employee in a company Each employee object handles the processing and data management related to that employee SEEM 3460 13

Classes and Objects An object is defined by a class A class is the blueprint of an object The class uses methods to define the behaviors of the object The class that contains the main method of a Java program represents the entire program A class represents a concept, and an object represents the embodiment of that concept Multiple objects can be created from the same class SEEM 3460 14

Classes and Objects class (the concept) object (the realization) Bank Account John s Bank Account Balance: $5,257 Multiple objects from the same class Bill s Bank Account Balance: $1,245,069 Mary s Bank Account Balance: $16,833 SEEM 3460 15

Java Translation The Java compiler translates Java source code into a special representation called bytecode Java bytecode is not the machine language for any traditional CPU Another software tool, called an interpreter, translates bytecode into machine language and executes it Therefore the Java compiler is not tied to any particular machine Java is considered to be architecture-neutral 16

Java Translation Java source code Bytecode interpreter machine code for target machine 1 Java compiler Java bytecode Bytecode interpreter machine code for target machine 2 17

Development Environments There are many programs that support the development of Java software, including: Sun Java Development Kit (JDK) Sun NetBeans IBM Eclipse Borland JBuilder MetroWerks CodeWarrior BlueJ jgrasp Though the details of these environments differ, the basic compilation and execution process is essentially the same SEEM 3460 18

Compiling and Running Java on Unix We can compile a Java program under Unix by: sepc92> javac Countdown.java If the compilation is successful, a bytecode file called Countdown.class will be generated. To invoke Java bytecode interpreter, we can: sepc92> java Countdown Three Two One.. Zero Liftoff! Houston, we have a problem. SEEM 3460 19

Variables A variable is a name for a location in memory A variable must be declared by specifying the variable's name and the type of information that it will hold data type variable name int total; int count, temp, result; Multiple variables can be created in one declaration SEEM 3460 20

Variable Initialization A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149; When a variable is referenced in a program, its current value is used SEEM 3460 21

Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; The expression on the right is evaluated and the result is stored in the variable on the left The value that was in total is overwritten You can only assign a value to a variable that is consistent with the variable's declared type SEEM 3460 22

Constants A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence As the name implies, it is constant, not variable The compiler will issue an error if you try to change the value of a constant In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; SEEM 3460 23

Constants Constants are useful for three important reasons First, they give meaning to otherwise unclear literal values For example, MAX_LOAD means more than the literal 250 Second, they facilitate program maintenance If a constant is used in multiple places, its value need only be updated in one place Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers SEEM 3460 24

Primitive Data There are eight primitive data types in Java Four of them represent integers: byte, short, int, long Two of them represent floating point numbers: float, double One of them represents characters: char And one of them represents boolean values: boolean SEEM 3460 25

Numeric Primitive Data The difference between the various numeric primitive types is their size, and therefore the values they can store: Type Storage Min Value Max Value byte short int long 8 bits 16 bits 32 bits 64 bits -128-32,768-2,147,483,648 < -9 x 10 18 127 32,767 2,147,483,647 > 9 x 10 18 float double 32 bits 64 bits +/- 3.4 x 10 38 with 7 significant digits +/- 1.7 x 10 308 with 15 significant digits SEEM 3460 26

Characters A char variable stores a single character Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' Example declarations: char topgrade = 'A'; char terminator = ';', separator = ' '; Note the distinction between a primitive character variable, which holds only one character, and a String object, which can hold multiple characters SEEM 3460 27

Character Sets A character set is an ordered list of characters, with each character corresponding to a unique number A char variable in Java can store any character from the Unicode character set The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters It is an international character set, containing symbols and characters from many world languages SEEM 3460 28

Characters The ASCII character set is older and smaller than Unicode, but is still quite popular The ASCII characters are a subset of the Unicode character set, including: uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, a, b, c, period, semi-colon, 0, 1, 2, &,, \, carriage return, tab,... SEEM 3460 29

Boolean A boolean value represents a true or false condition The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable can also be used to represent any two states, such as a light bulb being on or off SEEM 3460 30

Expression An expression is a combination of one or more operators and operands Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder + - * / % If either or both operands used by an arithmetic operator are floating point, then the result is a floating point SEEM 3460 31

Division and Remainder If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3 equals 8 / 12 equals 4 0 The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % 3 equals 8 % 12 equals 2 8 SEEM 3460 32

Operator Precedence Operators can be combined into complex expressions result = total + count / max - offset; Operators have a well-defined precedence which determines the order in which they are evaluated Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order SEEM 3460 33

Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e 1 2 3 4 a + b * c - d / e 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 SEEM 3460 34

Expression Tree The evaluation of a particular expression can be shown using an expression tree The operators lower in the tree have higher precedence for that expression + a + (b c) / d a / - d b c SEEM 3460 35

Assignment Revisited The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side SEEM 3460 36

Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value) SEEM 3460 37

Increment and Decrement The increment and decrement operators use only one operand The increment operator (++) adds one to its operand The decrement operator (--) subtracts one from its operand The statement count++; is functionally equivalent to count = count + 1; 38

Increment and Decrement The increment and decrement operators can be applied in postfix form: or prefix form: count++ ++count When used as part of a larger expression, the two forms can have different effects Because of their subtleties, the increment and decrement operators should be used with care 39

Increment and Decrement Suppose count has a value of 15 Consider the following statement: total = count++ After the assignment, total has a value of 15, whereas count has a value of 16 Consider the following statement: total = ++count Both total and count have a value of 16 40

Assignment Operators Often we perform an operation on a variable, and then store the result back into that variable Java provides assignment operators to simplify that process For example, the statement is equivalent to num += count; num = num + count; 41

Assignment Operators There are many assignment operators in Java, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y 42

Assignment Operators The right hand side of an assignment operator can be a complex expression The entire right-hand expression is evaluated first, then the result is combined with the original variable Therefore result /= (total-min) % num; is equivalent to result = result / ((total-min) % num); 43

Assignment Operators The behavior of some assignment operators depends on the types of the operands If the operands to the += operator are strings, the assignment operator performs string concatenation The behavior of an assignment operator (+=) is always consistent with the behavior of the corresponding operator (+) SEEM 3460 44

String Concatenation The string concatenation operator (+) is used to append one string to the end of another "Peanut butter " + "and jelly" It can also be used to append a number to a string A string literal cannot be broken across two lines in a program See Facts.java The println method can print a character string SEEM 3460 45

//******************************************************** // Facts.java // // Demonstrates the use of the string concatenation operator and the // automatic conversion of an integer to a string. //******************************************************* public class Facts { //----------------------------------------------------------------- // Prints various facts. //----------------------------------------------------------------- public static void main (String[] args) { // Strings can be concatenated into one long string System.out.println ("We present the following facts for your " + "extracurricular edification:"); System.out.println (); // A string can contain numeric digits System.out.println ("Letters in the Hawaiian alphabet: 12"); // A numeric value can be concatenated to a string System.out.println ("Dialing code for Antarctica: " + 672); System.out.println ("Year in which Leonardo da Vinci invented " + "the parachute: " + 1515); System.out.println ("Speed of ketchup: " + 40 + " km per year"); } } SEEM 3460 46

String Concatenation The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, it adds them The + operator is evaluated left to right, but parentheses can be used to force the order SEEM 3460 47

Escape Sequences What if we wanted to print a the quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\) System.out.println ("I said \"Hello\" to you."); SEEM 3460 48

Escape Sequences Some Java escape sequences: Escape Sequence \b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash SEEM 3460 49

Character Strings A string of characters can be represented as a string literal by putting double quotes around the text: Examples: "This is a string literal." "123 Main Street" "X" Every character string is an object in Java, defined by the String class Every string literal represents a String object SEEM 3460 50

The println Method In the previous Lincoln program, we invoked the println method to print a character string System.out is a built-in object representing a destination (the monitor screen) to which we can send output System.out.println ("Whatever you are, be a good one."); object method name information provided to the method (parameters) SEEM 3460 51

The print Method The System.out object provides another service as well The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line See Countdown.java SEEM 3460 52

//************************************************ // Countdown.java // // Demonstrates the difference between print and println. //************************************************ public class Countdown { //----------------------------------------------------------------- // Prints two lines of output representing a rocket countdown. //----------------------------------------------------------------- public static void main (String[] args) { System.out.print ("Three... "); System.out.print ("Two... "); System.out.print ("One... "); System.out.print ("Zero... "); System.out.println ("Liftoff!"); // appears on first output line } } System.out.println ("Houston, we have a problem."); SEEM 3460 53

Interactive Programs Programs generally need input on which to operate The built-in Scanner class provides convenient methods for reading input values of various types A Scanner object (called scan) can be set up to read input from various sources, including the user typing values on the keyboard Keyboard input is represented by the System.in object SEEM 3460 54

Reading Input The following line creates a Scanner object, called scan, that reads from the keyboard: Scanner scan = new Scanner (System.in); The new operator creates the Scanner object, called scan Once created, the Scanner object (i.e. scan) can be used to invoke various input methods, such as nextline(): answer = scan.nextline(); SEEM 3460 55

Reading Input The Scanner class is part of the java.util class library, and must be imported into a program to be used See Echo.java The nextline method reads all of the input until the end of the line is found The details of object creation and class libraries are discussed later SEEM 3460 56

//************************************************************* // Echo.java // // Demonstrates the use of the nextline method of the Scanner class // to read a string from the user. //************************************************************* import java.util.scanner; public class Echo { //----------------------------------------------------------------- // Reads a character string from the user and prints it. //----------------------------------------------------------------- public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextline(); } } System.out.println ("You entered: \"" + message + "\""); SEEM 3460 57

Echo.java - Sample Execution The following is a sample execution of Echo.class sepc92> java Echo Enter a line of text: This is a line You entered: This is a line SEEM 3460 58

Input Tokens Unless specified otherwise, white space is used to separate the elements (called tokens) of the input White space includes space characters, tabs, new line characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as nextint and nextdouble read data of particular types See GasMileage.java SEEM 3460 59

//************************************************************* // GasMileage.java // // Demonstrates the use of the Scanner class to read numeric data. //************************************************************* import java.util.scanner; public class GasMileage { //----------------------------------------------------------------- // Calculates fuel efficiency based on values entered by the // user. //----------------------------------------------------------------- public static void main (String[] args) { int miles; double gallons, mpg; Scanner scan = new Scanner (System.in); System.out.print ("Enter the number of miles: "); miles = scan.nextint(); System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextdouble(); mpg = miles / gallons; } } System.out.println ("Miles Per Gallon: " + mpg); SEEM 3460 60

GasMileage.java - Sample Execution The following is a sample execution of GasMileage.class sepc92> java GasMileage Enter the number of miles: 34 Enter the gallons of fuel used: 17 Miles Per Gallon: 2.0 SEEM 3460 61

Writing Classes Now we will begin to design programs that rely on classes that we write ourselves The class that contains the main method is just the starting point of a program True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality SEEM 3460 62

Designing Classes and Objects An object has state and behavior Consider a six-sided die (singular of dice) It s state can be defined as which face is showing It s primary behavior is that it can be rolled We can represent a die in software by designing a class called Die that models this state and behavior The class serves as the blueprint for a die object We can then instantiate as many die objects as we need for any particular program SEEM 3460 63

Classes A class can contain data declarations and method declarations int size, weight; char category; Data declarations Method declarations SEEM 3460 64

Classes The values of the data define the state of an object created from the class The functionality of the methods define the behaviors of the object For our Die class, we might declare an integer that represents the current value showing on the face One of the methods would roll the die by setting that value to a random number between one and six SEEM 3460 65

Classes In general, a class share some similarities with structures in C Recall that a structure in C is a user-defined data type composed of some data fields and each field belongs to a certain data type or another structure type A class is also composed of some data fields. In addition to it, a class is also associated with some methods SEEM 3460 66

General Design of Objects and Classes In general, we should first declare an object reference Then, we allocate memory for the object AClass obj1; The first line declares an object reference obj1 belonging to a class called AClass obj1 = new AClass(); The second line uses the new operator to allocate some memory for an object (under the class AClass) and lets obj1 points to it The second line also invokes the AClass constructor, if exists, to initialize the data in the object obj1 Data fields for obj1 SEEM 3460 67

General Design of Objects and Classes Similar to structures in C, one can access the data fields of an object via the dot operator For example, suppose in the class AClass, there are some data fields declared such as field1 and field2. Then, we can access field1 in obj1 via: obj1.field1 = 100; We can process an object by a method specified in the corresponding class via dot operator Suppose in the class AClass, there are some methods declared such as method1 and method2 Then we can process the object obj1 by method1 via: a_value = obj1.method1(); SEEM 3460 68

Creating Objects Another Example A variable holds either a primitive type or a reference to an object A class name can be used as a type to declare an object reference variable String title; An object reference variable holds the address of an object The object itself must be created separately Generally, we use the new operator to create an object title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object SEEM 3460 69

Creating Objects - Instantiation Creating an object is called instantiation An object is an instance of a particular class SEEM 3460 70

Invoking Methods We've seen that once an object has been instantiated, we can use the dot operator to invoke its methods count = title.length() A method may return a value, which can be used in an assignment or expression A method invocation can be thought of as asking an object to perform a service SEEM 3460 71

Object References Note that a primitive variable contains the value itself, but an object variable contains the address of the object An object reference can be thought of as a pointer to the location of the object Rather than dealing with arbitrary addresses, we often depict a reference graphically num1 38 title1 "Steve Jobs" SEEM 3460 72

A Complete Example of Classes and Objects Return to the example of our Die class For our Die class, we might declare an integer that represents the current value showing on the face One of the methods would roll the die by setting that value to a random number between one and six We ll want to design the Die class with other data and methods to make it a versatile and reusable resource See RollingDice.java See Die.java SEEM 3460 73

//************************************************************* // RollingDice.java // // Demonstrates the creation and use of a user-defined class. //************************************************************* public class RollingDice { //----------------------------------------------------------------- // Creates two Die objects and rolls them several times. //----------------------------------------------------------------- public static void main (String[] args) { Die die1, die2; int sum; die1 = new Die(); die2 = new Die(); die1.roll(); die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); SEEM 3460 74 SEEM 3460 74

} } die1.roll(); die2.setfacevalue(4); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); sum = die1.getfacevalue() + die2.getfacevalue(); System.out.println ("Sum: " + sum); sum = die1.roll() + die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); System.out.println ("New sum: " + sum); SEEM 3460 75 SEEM 3460 75

//************************************************************* // Die.java // // Represents one die (singular of dice) with faces showing values // between 1 and 6. //************************************************************* public class Die { private final int MAX = 6; // maximum face value private int facevalue; // current value showing on the die //----------------------------------------------------------------- // Constructor: Sets the initial face value. //----------------------------------------------------------------- public Die() { facevalue = 1; } SEEM 3460 76 SEEM 3460 76

//----------------------------------------------------------------- // Rolls the die and returns the result. //----------------------------------------------------------------- public int roll() { facevalue = (int)(math.random() * MAX) + 1; return facevalue; } //----------------------------------------------------------------- // Face value mutator. //----------------------------------------------------------------- public void setfacevalue (int value) { facevalue = value; } //----------------------------------------------------------------- // Face value accessor. //----------------------------------------------------------------- public int getfacevalue() { return facevalue; } SEEM 3460 77 SEEM 3460 77

//----------------------------------------------------------------- // Returns a string representation of this die. //----------------------------------------------------------------- public String tostring() { String result = Integer.toString(faceValue); } } return result; SEEM 3460 78 SEEM 3460 78

The Die Class The Die class contains two data values a constant MAX that represents the maximum face value an integer facevalue that represents the current face value The roll method uses the random method of the Math class to determine a new face value There are also methods to explicitly set and retrieve the current face value at any time SEEM 3460 79

Data Scope The scope of data is the area in a program in which that data can be referenced (used) Data declared at the class level can be referenced by all methods in that class Data declared within a method can be used only in that method Data declared within a method is called local data In the Die class, the variable result is declared inside the tostring method -- it is local to that method and cannot be referenced anywhere else SEEM 3460 80

Instance Data The facevalue variable in the Die class is called instance data because each instance (object) that is created has its own version of it A class declares the type of the data, but it does not reserve any memory space for it Every time a Die object is created, a new facevalue variable is created as well The objects of a class share the method definitions, but each object has its own data space That's the only way two objects can have different states SEEM 3460 81

Instance Data We can depict the two Die objects from the RollingDice program as follows: die1 facevalue 5 die2 facevalue 2 Each object maintains its own facevalue variable, and thus its own state SEEM 3460 82

The tostring Method All classes that represent objects should define a tostring method The tostring method returns a character string that represents the object in some way It is called automatically when an object is concatenated to a string or when it is passed to the println method SEEM 3460 83

Constructors A constructor is a special method that is used to set up an object when it is initially created A constructor has the same name as the class and it has no return data type The Die constructor is used to set the initial face value of each new die object to one We examine constructors in more detail later SEEM 3460 84

RollingDice.java - Compilation Assume that both RollingDice.java and Die.java are stored under the same directory in an Unix account To compile under Unix platform, we can simply compile the RollingDice.java: sepc92> javac RollingDice.java The compiler will first compile RollingDice.java. When it finds out that it needs to make use of the class Die.java. It will automatically compile Die.java If the compilation is successful, you can find two bytecodes, namely, RollingDice.class and Die.class If there is compilation error, the error message will be displayed on the terminal. If you wish to make the error message be displayed screen by screen, you can compile in the following way: sepc92> javac RollingDice.java & more SEEM 3460 85

RollingDice.java - Sample Execution The following is a sample execution of RollingDice.class sepc92> java RollingDice Die One: 6, Die Two: 1 Die One: 4, Die Two: 4 Sum: 8 Die One: 3, Die Two: 2 New sum: 5 SEEM 3460 86

Assignment Revisited In traditional programming language (non object-oriented) such as C, we can declare variables and conduct assignment on variables The act of assignment takes a copy of a value and stores it in a variable For example, consider the integer variables: int num1, num2; num2 = num1; Before: num1 38 num2 96 After: num1 38 num2 38 SEEM 3460 87

Reference Assignment For object references, assignment copies the address For example, suppose that name1 and name2 are two object references Before: title1 title2 "Steve Jobs" "Steve Wozniak" title2 = title1; After: title1 title2 "Steve Jobs" SEEM 3460 88

Aliases Two or more references that refer to the same object are called aliases of each other That creates an interesting situation: one object can be accessed using multiple reference variables Aliases can be useful, but should be managed carefully Changing an object through one reference changes it for all of its aliases, because there is really only one object SEEM 3460 89

Class Libraries A class library is a collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment Its classes are not part of the Java language per se, but we rely on them heavily Various classes we've already used (System, Scanner, String) are part of the Java standard class library Other class libraries can be obtained through third party vendors, or you can create them yourself SEEM 3460 90

Packages The classes of the Java standard class library are organized into packages Some of the packages in the standard class library are: Package Purpose java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing SEEM 3460 91

The import Declaration When you want to use a class from a package, you could use its fully qualified name java.util.scanner Or you can import the class, and then use just the class name import java.util.scanner; To import all classes in a particular package, you can use the * wildcard character import java.util.*; SEEM 3460 92

The import Declaration All classes of the java.lang package are imported automatically into all programs It's as if all programs contain the following line: import java.lang.*; That's why we didn't have to import the System or String classes explicitly in earlier programs The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported SEEM 3460 93

The Random Class The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values See RandomNumbers.java SEEM 3460 94

//************************************************************* // RandomNumbers.java // // Demonstrates the creation of pseudo-random numbers using the // Random class. //************************************************************* import java.util.random; public class RandomNumbers { //----------------------------------------------------------------- // Generates random numbers in various ranges. //----------------------------------------------------------------- public static void main (String[] args) { Random generator = new Random(); int num1; float num2; num1 = generator.nextint(); System.out.println ("A random integer: " + num1); SEEM 3460 95 SEEM 3460 95

} } num1 = generator.nextint(10); System.out.println ("From 0 to 9: " + num1); num1 = generator.nextint(10) + 1; System.out.println ("From 1 to 10: " + num1); num1 = generator.nextint(15) + 20; System.out.println ("From 20 to 34: " + num1); num1 = generator.nextint(20) - 10; System.out.println ("From -10 to 9: " + num1); num2 = generator.nextfloat(); System.out.println ("A random float (between 0-1): " + num2); num2 = generator.nextfloat() * 6; // 0.0 to 5.999999 num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); SEEM 3460 96 SEEM 3460 96

RandomNumbers.java - Sample Execution The following is a sample execution of RandomNumbers.class sepc92> java RandomNumbers A random integer: -1709988757 From 0 to 9: 2 From 1 to 10: 9 From 20 to 34: 31 From -10 to 9: 1 A random float (between 0-1): 0.7517807 From 1 to 6: 2 SEEM 3460 97

Encapsulation We can take one of two views of an object: internal - the details of the variables and methods of the class that defines it external - the services that an object provides and how the object interacts with the rest of the system From the external view, an object is an encapsulated entity, providing a set of specific services These services define the interface to the object SEEM 3460 98

Encapsulation An encapsulated object can be thought of as a black box -- its inner workings are hidden from the client The client invokes the interface methods of the object, which manages the instance data Client Methods Data SEEM 3460 99

Method Declarations Let s now examine method declarations in more detail A method declaration specifies the code that will be executed when the method is invoked (called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined SEEM 3460 100

Method Control Flow If the called method is in the same class, only the method name is needed compute mymethod mymethod(); SEEM 3460 101

Method Control Flow The called method is often part of another class or object main doit helpme obj.doit(); helpme(); SEEM 3460 102

Method Header A method declaration begins with a method header char calc (int num1, int num2, String message) return type method name parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter SEEM 3460 103

Method Body The method header is followed by the method body char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charat (sum); } return result; sum and result are local data The return expression must be consistent with the return type They are created each time the method is called, and are destroyed when it finishes executing SEEM 3460 104

The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type A return statement specifies the value that will be returned return expression; Its expression must conform to the return type SEEM 3460 105

Parameters When a method is called, the actual parameters in the invocation are copied into the formal parameters in the method header ch = obj.calc (25, count, "Hello"); char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charat (sum); } return result; SEEM 3460 106

Local Data As we ve seen, local variables can be declared inside a method The formal parameters of a method create automatic local variables when the method is invoked When the method finishes, all local variables are destroyed (including the formal parameters) Keep in mind that instance variables, declared at the class level, exists as long as the object exists SEEM 3460 107

Bank Account Example Let s look at another example that demonstrates the implementation details of classes and methods We ll represent a bank account by a class named Account It s state can include the account number, the current balance, and the name of the owner An account s behaviors (or services) include deposits and withdrawals, and adding interest SEEM 3460 108

Driver Programs A driver program drives the use of other, more interesting parts of a program Driver programs are often used to test other parts of the software The Transactions class contains a main method that drives the use of the Account class, exercising its services See Transactions.java See Account.java SEEM 3460 109

//************************************************************* // Transactions.java // // Demonstrates the creation and use of multiple Account objects. //************************************************************* public class Transactions { //----------------------------------------------------------------- // Creates some bank accounts and requests various services. //----------------------------------------------------------------- public static void main (String[] args) { Account acct1 = new Account ("Ted Murphy", 72354, 102.56); Account acct2 = new Account ("Jane Smith", 69713, 40.00); Account acct3 = new Account ("Edward Demsey", 93757, 759.32); acct1.deposit (25.85); double smithbalance = acct2.deposit (500.00); System.out.println ("Smith balance after deposit: " + smithbalance); SEEM 3460 110 SEEM 3460 110

} } System.out.println ("Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50)); acct1.addinterest(); acct2.addinterest(); acct3.addinterest(); System.out.println (); System.out.println (acct1); System.out.println (acct2); System.out.println (acct3); SEEM 3460 111 SEEM 3460 111

//************************************************************* // Account.java // // Represents a bank account with basic services such as deposit // and withdraw. //************************************************************* import java.text.numberformat; public class Account { private final double RATE = 0.035; // interest rate of 3.5% private long acctnumber; private double balance; private String name; //----------------------------------------------------------------- // Sets up the account by defining its owner, account number, // and initial balance. //----------------------------------------------------------------- public Account (String owner, long account, double initial) { name = owner; acctnumber = account; balance = initial; } SEEM 3460 112 SEEM 3460 112

//----------------------------------------------------------------- // Deposits the specified amount into the account. Returns the // new balance. //----------------------------------------------------------------- public double deposit (double amount) { balance = balance + amount; } return balance; //----------------------------------------------------------------- // Withdraws the specified amount from the account and applies // the fee. Returns the new balance. //----------------------------------------------------------------- public double withdraw (double amount, double fee) { balance = balance - amount - fee; } return balance; SEEM 3460 113 SEEM 3460 113

//----------------------------------------------------------------- // Adds interest to the account and returns the new balance. //----------------------------------------------------------------- public double addinterest () { balance += (balance * RATE); return balance; } //----------------------------------------------------------------- // Returns the current balance of the account. //----------------------------------------------------------------- public double getbalance () { return balance; } //----------------------------------------------------------------- // Returns a one-line description of the account as a string. //----------------------------------------------------------------- public String tostring () { NumberFormat fmt = NumberFormat.getCurrencyInstance(); } } return (acctnumber + "\t" + name + "\t" + fmt.format(balance)); SEEM 3460 114 SEEM 3460 114

Transactions.java - Sample Execution The following is a sample execution of Transactions.class sepc92> java Transactions Smith balance after deposit: 540.0 Smith balance after withdrawal: 107.75 72354 Ted Murphy $132.90 69713 Jane Smith $111.52 93757 Edward Demsey $785.90 SEEM 3460 115

Bank Account Example acct1 72354 acctnumber balance 102.56 name Ted Murphy acct2 69713 acctnumber balance name 40.00 Jane Smith SEEM 3460 116

Constructors Revisited Note that a constructor has no return type specified in the method header, not even void A common error is to put a return type on a constructor, which makes it a regular method that happens to have the same name as the class The programmer does not have to define a constructor for a class Each class has a default constructor that accepts no parameters SEEM 3460 117