Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes...

59
Java Chapter 2 Creating Classes

Transcript of Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes...

Page 1: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Java

Chapter 2

Creating Classes

Page 2: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Class

Defines structure of an object or set of objects;

Includes variables (data) and methods (actions) which determine how an object behaves

Page 3: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Construction a Data Declaration Section Variable classifications:

Instance – within a class but outside a method. Every object created receives a variable of this type. The keyword static may not be used.

Example: public class Date int year; int month; int day;Position: top of a class’s body. Values vary for each

different instance of an object of that class.

Page 4: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Class variable

Class – located within a class’s body but outside any method. The keyword static must be used.

e.g. p public class Date

static double time; public static final int YEAR = 1583;

Note the modifier “final” – indicates that the variable YEAR is a constant. Note capitalization.

Page 5: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Local Variables Local – within a method body. Neither an access

specifier nor the keyword static may be used.public static void main (String[] args)

{double payRate;int employeeNumber;. . .

parameter – within the () of a method’s header line. Neither an access specifier nor the keyword static may be used.

public double area (double length; double width){ . . .

Page 6: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Declaration Statements

1. Naming a variable optionalAcccessSpecifier dataType variableName

e. g. private double totalDebits Use identifier rules

2. Initializing a variable’s value If already declared: totalDebits = 4982.34; If undeclared: private int age = 22; Watch out for floats: float amtOwed = 27.39 is

incorrect

Page 7: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Task: Construct a program to calculate floor area In what terms could we define the floor? What datatype should we use?

private double width;(Reserved word private used almost universally for all

instance variables) private double length;

Do I need to declare a variable area?

Page 8: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Data types

Primitive vs. ReferenceSee p. 61 in text

Note that with floats – always add either f or F to the literal values

float tax = 0.0825f; Escape sequences – p. 67

Page 9: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Objectives

You should be able to describe: Data Values and Arithmetic Operations Constructing a Data Declaration Section:

Variables Completing the Class: Methods Assignment Operations

Page 10: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Objectives (continued)

Program Design and Development: Object Identification

Common Programming Errors

Page 11: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Data Values and Arithmetic Operations General data types:

Primitive Reference

Literal Value that explicitly identifies itself Example:

1 “xyz”

Page 12: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Data Values and Arithmetic Operations (continued)

Figure 2.1: Primitive data types

Page 13: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Data Values and Arithmetic Operations (continued)

Figure 2.2: Reference types

Page 14: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Integer Literals

Zero or any positive or negative numerical value without decimal point

Examples: 1 -406 352563

Other data types: Byte Short integer

Page 15: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Integer Literals (continued)

Table 2.1: Integer Data Types

Page 16: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Floating-Point Values

Also called real numbers Numerical value with decimal point Examples:

-1.24 0.0 2435.34

Data types: Double Float

Page 17: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Floating-Point Values (continued)

Table 2.2: Floating-Point Data Types

Page 18: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Character Values

Letters of alphabet Both uppercase and lowercase

10 digits 0 through 9 Special symbols such as 1 $ . , - ! Stored as 16-bit unsigned values using

Unicode

Page 19: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Escape Sequences

\ before characters Tells compiler to execute differently from

normal behavior

Page 20: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Escape Sequences (continued)

Table 2.4: Escape Sequences

Page 21: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Boolean Values

Restricted to one of two values: True False

Page 22: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Arithmetic Operations

Used for mathematical calculations Operators:

Addition: + Subtraction: - Multiplication: * Division: / Modulus: %

Page 23: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Arithmetic Operations (continued) Simple arithmetic expression Integer expression Real expression Mixed-mode expression Overloaded operator

Symbol represents more than one operation Execution depends on types of operands

encountered (e.x. 2 + 3.354)

Page 24: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Integer Division

Division of two integers can produce strange results for unwary

Integers cannot contain fractional part It is dropped

Example: 15/7 = 2

Page 25: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

The Modulus Operator

Retain remainder of division Operator symbol:

% Example:

9.2 % 4 = 1.2 15 % 4 = 3

Page 26: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Negation

Unary operator One that operates on single operand

Same symbol as binary subtraction (-) Negates or reverses number

Page 27: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Negation (continued)

Table 2.6: Summary of Arithmetic Operations

Page 28: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Operator Precedence and Associativity Rules for working with arithmetic operators:

Two binary arithmetic operator symbols must never be placed side by side

Parentheses may be used to form groupings Expressions in parentheses are evaluated first

Parentheses can be nested Parentheses cannot be used to indicate

multiplication

Page 29: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Operator Precedence and Associativity (continued) Order of operations:

All negations are done first Multiplication, division, and modulus

operations are computed first Addition and subtraction are computed last

Page 30: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

String Concatenation

Joins two or more strings into single string Only operation that directly manipulates

string data in similar fashion as numerical data

Has same precedence as addition operator Always use parentheses when performing

arithmetic operations in any expression that contains a string

e.g. “The sum is” + 10 +20 producesThe sum is 1020

Page 31: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Constructing a Data Declaration Section: Variables Values in computer program are stored and

retrieved from computer’s memory unit Variable:

Name given by programmer Refers to computer storage locations that

store primitive data type value Selection of variable names is left to

programmer

Page 32: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Constructing a Data Declaration Section Classifications of variables:

Instance Class Local Parameter

Dependent on: Variable placement within class Presence or absence of reserved word static

Page 33: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Constructing a Data Declaration Section (continued)

Table 2.8: Determination of Variable Types

Page 34: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Creating Objects

Objects Only created from instance variables declared

in data declaration section or from other object types

Methods Provide operations that can be applied to

created objects or create general-purpose functions Independent of any one object

Page 35: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Creating Objects (continued)

Figure 2.6: The RoomType class

Page 36: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Creating Objects (continued)

Using dynamic memory allocation operator also called: Creating an instance Instantiating an object

Reference variable Reference location in memory where actual

object’s values located

Page 37: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Creating Objects (continued)

Private Once object is created, its private variables

can only be accessed by its class methods Safety feature provided by object-oriented

languages Cleansing Memory

Memory leak problem Objects keep track of who references them JVM cleans unused memory

Page 38: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Creating Objects (continued)

Figure 2.8: Instantiating an object

Page 39: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Specifying Storage Allocation

Declaring variables protects against typos Compiler catches errors

Each data type has its own storage requirements Compiler pre-allocates memory based on data

type Definition statements

Statements that cause variables to be created

Page 40: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Completing the Class: Methods Classes provide methods to:

Initialize values stored in each instance variable to user-selected values

Display values Modify values

Format of method header: public returnType methodName(parameter list)

Public Means method can be used in other classes

Page 41: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Constructor Methods

Method that has same name as class Automatically called each time object created Purpose:

Initialize new object’s instance variables Format:public ClassName(parameter list)

{

method body

}

Page 42: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Accessor Methods

Provide means for reading values stored in object’s variables

Referred to as get() method

Page 43: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Mutator Methods

Provide means for changing object’s values After object created

Also known as set() methods

Page 44: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Convenience

Can be convenient to place two classes in one file Second class’s main() method is placed

within first class’s methods section Both classes are stored in same file

public reserved word removed from class that does not contain main() method

Page 45: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Assignment Operations

Most basic statements for initializing variables

General syntax: variable = expression;

Example: length = 25;

Expression Any combination of constants and variables

that can be evaluated to yield a result

Page 46: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Assignment Operations (continued) All variables used in expression must

previously have been given valid values Must be a variable listed immediately to left of

equal sign Has lower precedence than any other

arithmetic operator

Page 47: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Multiple Declarations

Variables with same data type can be grouped Declared using single declaration statement

Frequently used in declaring method’s internal variables

Coercion Forced conversion based on data types

Page 48: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Assignment Variations

In an assignment expression: Variable to left of equal sign can also be used

to right of equal sign Shortcut assignment operators:

+= -= *= /= %=

Page 49: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Accumulating

Values added to program variable as program progresses

Uses assignment operator: sum = sum + 10,

Page 50: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Counting

Counting statement form: variable = variable + fixedNumber;

Example: i = i + 1;

Increment/decrement operators: ++ -- Example:

i++

Page 51: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Procedural versus Object Orientations Procedure-oriented programming

Emphasis on operations to be performed Object-oriented programming

Emphasis on attributes and behavior of objects

Page 52: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Common Programming Errors Forgetting to declare all variables used in

class Forgetting to assign or initialize values for all

variables before variables are used in expression

Mixing data types in same expression without clearly understanding effect produced

Defining more than one default constructor for class

Page 53: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Summary

Primitive data types: Numerical Boolean

Every variable must be declared as to type of value it can store

Class Programmer-defined data type

Page 54: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Summary (continued)

Classes contain methods: Constructor Accessor Mutator

Expressions evaluated according to precedence and associativity of operators used

Assignment symbol operator: =

Page 55: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

Creating Objects

public class UseRoomType{ public static void main(String[] args) { RoomType roomOne; // declare a variable of type RoomType

roomOne = new RoomType(); // create and // initialize an object of type RoomType }}

Page 56: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

RoomType roomOne; roomOne declared as a variable of type RoomType.Notice the capitalizations– what does that indicate?

roomOne is a programmer devised variableRoomType is a class

Why can’t we declareprivate RoomType roomOne; ?Ans: placed within a method and all variables declared

in a method are local and therefore privateThe contents of the memory storage of roomOne is

null because it does not yet refer to a valid object. It is a reference variable.

Page 57: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

The RoomType class

public class RoomType{ // data declarations section private double length; // declare length as a double variable private double width; // declare width as a double variable

}

Page 58: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

The process of creating a new object using the dynamic memory allocation operator is referred to as both creating an instance and instantiating an object.

Length and width – instance variables: an instance of them only comes into existence when an object is created.

Each created object will contain one instance of each instance variable

The variable is referenced using the object’s name – e.g.

roomOne.length or roomTwo.length

Page 59: Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.

// File:DemoOperators.java// Description: Test program// This program will test the combination of integers and real numbers// and will explore the modulus operator// Programmer: M. Markel

// Date: 2/07

public class DemoOperators{ public static void main(String[] args) { System.out.println("9/2 = "+ 9/2); System.out.println("9%2 = "+ 9%2); System.out.println("9.0/2 = "+ 9.0/2);

System.out.println("9/2.0 = "+ 9/2.0); System.out.println("9.0%2 = "+ 9%2);System.out.println("9.0f/2 = "+ 9.0f/2);System.out.println("9.0/1.2 = "+ 9.0/1.2);System.out.println("9.0%1.2 = "+ 9.0%1.2);

414.54.514.57.50.600000000000003