Title: Content
1Unit 3 Classes and Objects
- Content
- Defining Classes in Java Programs
- Manipulating Objects
- What can Java Programs manipulates ?
- Choosing suitable attribute types
- Manipulating DATA
- Class packages
- Class members
2A) Defining Classes in Java Programs
pp-3
- To declare a class in Java program
- order of variable method declarations is
arbitrary - can even mix them.
- data centric
- mainly concerns about data
- place variable declaration before method
declaration - behavior centric
- mainly concerns about behaviors,
- place method declaration before the variable
declaration
class class-name variable-declarations
method-declarations
3Use of comments
- a good practice to make programs self-explanatory
- by adding some remarks or comments
- Java compiler will ignore all comments
- ways to add comments in Java program
- Use / / pair for single-line or comment
block - Use // to add single-line comment. Everything
after the slashes is considered to be comments - starting with "/" and ending with "/" for
documentations ( comment block )
4- / ---------------------------------
- This is a comment BLOCK-1
- gtgtgt for documentation ltltlt
- ---------------------------------
- /
- public class HelloWorld
- / Comment line-1 /
- // Comment line-2
- public static void main (String args) /
Comment line-4 / - System.out.println("Hello World") //
Comment line-3 -
-
- // ----------------------------------
- // This is a comment BLOCK-2
- // created using many comments LINES
5Naming classes and class members
- identifier
- names of classes, variables and methods
- may consist of any letters, digits, and _
- must start with letters, digits, or
_ - no limit on the length
- valid identifier money, _yourStuff
- invalid identifier 201Marks, path
- class identifiers should start with uppercase
letters - eg. Account, SavingsAccount
- identifiers of method names are verbs, start with
lowercase - eg. deposit()
- identifiers for variables are nouns, start with
lowercase - eg. interest, accountBalance
6Keywords
- are building blocks of Java language, and
- each has its own meaning
- so, we cannot use these keywords as identifiers
- indicates a keyword that is not currently used
- indicates a keyword that was added for Java 2
- true, false null are reserved words with
pre-defined values - All keywords and reserved words are in
lowercase.
abstract const finally int public this
boolean continue float interface return throw
break default for long short throws
byte do goto native static transient
case double if new strictfp try
catch else implements package super void
char extends import private switch volatile
class final instanceof protected synchronized while
7Defining Attributes
use , as a delimiter to separate attributes
- To declare attributes in a class definition
- type identifier
- type identifier1 , idenfiter2
- double balance, overdrawnLimit
- a variable is a memory location that stores a
value - The variables above, balance and overdrawnLimit,
are also called instance variables, because when
we create an object, the computer allocates
memory for each object to store the attribute
values - should choose a variable name that suggests what
data it stores - should use int to store integral
value. - should use double to store floating-point value
8Defining Methods
pp-9
return-type method-name( parameter-list )
variable-declarations statements
void increase () reading reading 1
9class name
ticketCounter
reading 1
reading 0
attribute it value
1
- void is used when a method returns nothing
- statements can span more than one line but must
be terminated by a semi-colon - The equals sign is to assign the value of the
expression on the right-hand side to the variable
on the left-hand side. - every time an object performs an operation or
behavior, the operations are applied on its own
attributes
10- the return keyword
- the value to be returned must match the return
type preceding the method name in the method
declaration. - The order of the method declaration is arbitrary.
- Its up to us to use our own conventions.
class TicketCounter int reading // The ticket
counter reading // To GET the ticket counter
reading public int getReading() return
reading
11- /
- The class definition of a Ticket Counter
(pp-34 U3) -
- /
- class TicketCounter
- int reading // The ticket counter reading
- // -----------------------------------------------
--- - // To increase the reading by one
- public void increase()
- reading reading 1
-
- // ---------------------------------------------
----- - // increment reading specified by a parameter,
amount - public void increaseByAmount(int amount)
- reading reading amount
-
- // ---------------------------------------------
----- - // To GET the ticket counter reading
- public int getReading()
attributes
operations are applied on its own attributes
method parameters
the returned value must match the data type of
the method
The order of method declaration is arbitrary
12local variable vs. instance variable
- local variable is declared in a method
- same syntax as declaring instance variable
- local variable declaration is placed within a
method definition, whereas an instance variable
definition is placed within a class definition
outside of all method definitions. - local variables are created when the method is
executed. When the computer completes the method
execution, it automatically removes these
variables. By contrast, instance variables last
as long as the object that contains them.
13local variable vs. instance variable
Local ( Temporary ) Instance
declared in a method outside of all method definitions
cannot be accessed by other methods can be accessed by all methods
will be removed after execution persistent
eg. radius eg. diameter
class Circle double diameter public
double calculateCircleArea() double radius
diameter / 2.0 return 3.1414 radius radius
instance variable
local variable
14B) Manipulating objects
pp-16
- generic way to create an object
- or
- eg.
- or
- We can visualize it as follows
Class-name variable-name variable-name new
Class-name()
Class-name variable-name new Class-name()
TicketCounter counter counter new
TicketCounter()
TicketCounter counter new TicketCounter()
it is a memory location a box whose label is
counter
counter
counter is a reference variable
15- counter
- a variable, or a reference variable as it is used
to refer to an object while running a program. - a little box with a label counter telling us
how to find our ticket counter. - the way to find or get an object is known as a
reference or handle, thats why the variable is
called a reference variable - new
- is a keyword to create an object
- The parentheses that follow the class name,
TicketCounter, are mandatory - Besides of object creation, new tells us where
to find the object the reference to the newly
created object
16null literal
pp-20
- to indicate a variable that refers to nothing,
- If the counter variable was storing a reference
to an object, it loses that handle now.
counter null
17Implicit and explicit initialization
Implicit Explicit
during object creation during object creation
instance variables are initialized with default value instance variables are initialized with specific value
eg.
// The class definition for a bank account class
Account double balance
// Implicit double allowance 10000.0 //
Explicit // To overdraw an account public
void overdraw(double amount) allowance
allowance amount
18- to declare a few variables at the same time
- eg.
- or
Class-name variable-name1, variable-name2,
TicketCounter counter1 , counter2 counter1
new TicketCounter() counter2 new
TicketCounter()
TicketCounter counter1 new TicketCounter() ,
counter2 new TicketCounter()
19- counter1 counter2 are two different objects
- each has its own
- variable reading
- methods increase, .
counter1
counter2
20Accessing object members
pp-22
- use dot-notation
- eg. counter.reading
- assigning a value to the variable "reading" of
the TicketCounter object - Dont assign a value directly to an object
attribute - Please send a message to the object and let it
maintain its own attribute values - eg
counter.reading 10 // not recommended
counter.setReading(10) // preferable way
21- if following messages are sent
- well have
counter1.setReading(10) counter2.setReading(20)
counter1
counter2
22- example 1, pp2526
- from line-1, 2 variables are created
- from line-2, counter1 is created and the
reference is stored - from line-3, the content of counter1 is copied to
counter2 , so they are both referring to the same
object
TicketCounter counter1, counter2 //
line-1 counter1 new TicketCounter( ) //
line-2 counter2 counter1 // line-3
counter1
counter2
ticketCounter
counter1
reading
counter2
increase increseByAmount getReading setReading
ticketCounter
counter1
reading
counter2
increase increseByAmount getReading setReading
23TicketCounter counter1, counter2 //
line-1 counter1 new TicketCounter( ) //
line-2 counter2 new TicketCounter( ) //
line-3 counter1.setReading( 1 ) //
line-4 counter2.setReading( 2 ) //
line-5 counter2 counter1 //
line-6 counter2.setReading( 3 ) // line-7
- example 2 self-test 3.4
- after line-3, TWO
- counter objects are created
- after line-5
- after line-6, refers to only ONE object
counter2
counter1
ticketCounter
ticketCounter
reading
reading
setReading
setReading
counter2
counter1
ticketCounter
ticketCounter
reading 1
reading 2
setReading
setReading
counter2
counter1
ticketCounter
counter2
counter1
ticketCounter
reading 1
reading 3
setReading
setReading
24Access control Private vs Public
- further to Accessing object members (pp-22),
- to prevent direct access to an object attributes
method from other objects
// The class definition of a ticket counter /
page-34 / class TicketCounter private int
reading // reading can only be read by a
TickerCounter object // To increase the
reading by one public void increase()
reading reading 1 // To increase the
reading specified by the parameter, amount
public void increaseByAmount(int amount)
reading reading amount // To get the
ticket counter reading public int
getReading() return reading // To set a
value to the ticket counter reading public
void setReading(int newReading) reading
newReading
25C) What can Java Programs manipulates ?
Primitive data types Non-primitive types (or classes)
The word primitive means basic or fundamental. Any types other than the eight primitive data types are known as non-primitive types.
Eight primitive types boolean, byte, char, double, float, int, long, and short. non-primitive types can be used to model objects that have both attributes and behaviors
can be used immediately must new an instance before use
eg. int temperature temperature 20 eg. TicketCounter counternew TicketCounter()
26Java types
pp-64
Primitive data types
classes
Logical
Numeric
Textual
Textual
. . . . .
boolean
char 16-bit
String
Integral
Floating-Point
byte 8-bit
short 16-bit
int 32-bit
long 64-bit
float 32-bit
double 64-bit
27To declare a variable of any type
- general format
- eg.
- using the little box concept, their difference are
variable-type variable-name
variable-type variable-name int temperature
// declaring primitive type variable
TicketCounter counter // declaring
non-primitive type variable
Primitive data types Non-primitive types
a box stores the value a box stores a reference to a real object
28Integral types (primitive)
- can only store whole numbers (integers)
- four integral types
- byte , short , int and long
- they are all signed types
- the differences among them are
- the computer uses different memory sizes
- the range of values is different
- any integral literal is defaulted to int
- override with a suffix of letter L or l for long
64-bit storage - 10L or 5l
- use a prefix 0 for octal and prefix 0x or 0X for
hexadecimal - int var1 077 // 778
- int var2 0xABCD // ABCD16
29Real types or floating-point type (primitive)
- 'floating-point' means a decimal point is placed
freely between any two digits in a number, - eg. 1.23 and 45.67
- two different real types
- float and double (the default)
- both are signed
- Maximum value is the ones with the largest
magnitudes, which can either be positive or
negative. - Minimum value is the ones that are closest to
(but not absolutely) zero - To enforce 32 bits, overriding with a suffix F or
f (float) to the literal - float pi 3.14F // or 3.14f
- double e 2.71828
- to express a value in scientific notation
- for positive exponential, use 5.234E20 for 5.234
x 1020 - for negative exponential, use 1.4E-45 for 1.4 x
10-45
30Data type Whole number Memory size Range
byte yes 8 bits -128 to 127
short yes 16 bits -32768 to 32767
int yes 32 bits -2147483648 to 2147483647
long yes 64 bits -9223372036854775808 to 9223372036854775807
float no 32 bits Max 3.4028235x1038 Min 1.4x10-45
double no 64 bits Max 1.7976931348623157x10308 Min 4.9x10-324
31Character type (primitive)
- a textual type char (16-bit unsigned short in
nature) - can store any digit, letter, or special character
- characters are represented in 16-bit Unicode
- an English alphabet (letter) uses a single-byte
but a Chinese character uses double-byte - used with pairs of single quotation marks
- char size 'S'
- char specialChar '\uABCD' // Unicode ABCD16
- some special characters
- '\n ' new line character
- '\r ' carriage return ltentergt character
- '\t ' tab character
32Logical type (primitive)
String type (non-primitive)
- The char type can store only one character. If we
want to specify a text string, we need to use
String objects. - used with a pair of double quotation marks
- String course "MT201"
- String is class or non-primitive type
- one logical type boolean
- two possible values
- true and false (two pre-defined literals in Java)
- boolean isValid true
33Primitive type vs. Non-primitive type
pp-40
- Primitive type
- Declaring a primitive type variable allocates a
memory location that can store any acceptable
value - Dont use dot-notation with a primitive variable,
which refers to a datum that has no behavior and
no attribute,. - They are pre-defined, and we cannot build and use
our own primitive types - Non-primitive type
- Variables of non-primitive types are reference
types. - Declaring a non-primitive type variable allocates
a memory block that just stores the handle (or
reference) to an object in the memory, but no
object is created. - usually store their references in non-primitive
variables of compatible types
34example
int i, j Square x, y i 123 x new
Square() j i y x
123
i
j
123
x
Square
y
content of i is not changed by line-1
more
123
i
j 456 // line-1 y new Square()
j
456
x
Square
Square
y
35D) Choosing suitable attribute types
- to classify all attributes into different
primitive type, such as numeric, textual and
logical. - Numeric types
- attribute value is numeric may involve
calculations - usually concerned with its value rather than the
format - ie. the way to present it. So leading zeroes can
be ignored - eg. account balance, interest rate, day of birth,
month of birth, year of birth, day of account
opening, month of account opening, year of
account opening. - Textual types
- can include non-numeric characters.
- Its values are not used in numerical calculations
but for pattern matching (like account number). - has to consider Its storage format. Numbers with
leading zeros are considered as a textual type. - account name, owner identity number, account
type, account number, gender and address
36- Logical types
- for an attribute that can contain only two
values, such as positive/negative, yes/no,
true/false - active account (either active or inactive)
- more textual types
- if the textual attribute value has only one
character, we can assign char type to that
attribute - Otherwise, use a String type.
- char
- accountType (Ssavings Ccurrent account),
- gender (F for female and M for male)
- String
- accountName , address, studentNumber
37- more numeric types
- check if attribute value must contain fractional
parts (real type) or not (integer type) - integer dayOfBirth, monthOfBirth, yearOfBirth
- real accountBalance, interestRate
- check range of the attributes, so as to choose a
suitable type - the possible value of dayOfBirth and dayOfAccount
open is 1 to 31, so, the primitive type byte is
sufficient. - primitive type float is large enough to store any
possible value of account balance and interest
rate. - it is recommended to use int for all integral
attributes and double for attributes whose value
can contain fractions. The reason is that int and
double are the default types for integral
literals and real literals. If we use int and
double only, we can bypass many troublesome
restrictions in Java - such as the type conversions that would take
place during numerical calculations. As a result,
- int day of birth, month of birth, year of birth
- double account balance, interest rate
38- A variable of float or double type can store a
value with a fraction. - They can store integral values why dont we
simply declare all numeric types as real types? - The reason is
- Real numbers are stored by approximation, while
integral numbers are stored exactly. - Therefore, whenever it is possible to use an
integer type, we should use it so that we do not
face the risk of losing precision.
39- to consolidate co-related attributes into a class
- can derive a class definition that only contains
day, month and year - // The class definition of a date
- class Date
- int day
- int month
- int year
-
- then, we can declare the date of birth as
- Date dateOfBirth
40E) Manipulating DATA
- Assignment
- statement format
-
-
- Numerical calculations
variable expression
rate 0.07 b a 2 a 1 b 2 //
Syntax error allow only 1 variable on LHS of
int a 5, b 2 int c a / b // c 2
truncated fractional part of integer division
41Operator precedence
- precedence of the four operators
- first /, then -
- from left to right, if operators are at the same
level, - For example,
- double a 1.0, b 2.0, c 3.0, d 4.0
- double e a b c / d
- the result is determined as
- e a (b c )/ d
- e a 6.0 / d
- e a 1.5
- e 2.5
- we can use parentheses to alter the order of
processing - int a 1, b 2, c 3
- int d (a b) c
42Type conversions
- Generally, in an expression, the data type of
both the LHS and RHS of must be the same - In some cases, the computer will automatically
convert the value computed by the expression to
match the type of the variable (implicit
conversion), provided that - the variable is large enough to store the value
- by comparing the number of bits
- such variable on the LHS of an equals sign is
known as assignment compatible - the assignment will not lose its precision
- the fractional part of a real number is not lost
43pp-51
double (64-bit)
float (32-bit)
Real type
Integer type
long (64-bit)
int (32-bit)
short (16-bit)
char (16-bit)
byte (8-bit)
A value of a type that occurs lower in the above
diagram can be converted automatically to a value
that occurs higher. But it is not possible to do
it the other way round.
44Example
- long b 10 // OK int -gt long
- int c 10L // illegal int does not have
- // sufficient storage for long value
- // even though 10 is within int range
- double d 3.14F //OK float -gt double
- float f 3.1415 // illegal double cannot be
- // auto-converted to float
- float f 100 // OK int-gtfloat
- int j 0.0 // illegal 0.0 is real number and
- // if converted, fractional part
- // of the real number will be lost
45Remarks
- In Java, char type can be considered integer
type. - Both char and short are 16-bit data types and the
difference is their ranges. - but char can only store positive values (0 to
65535), while short can store both negative and
positive values(-32768 to 32767). - Because of this difference, they cannot be
implicitly converted to each other without losing
information
46Casting (explicit conversion )
pp-52
- Value of any data type can be assigned to a
variable of another data type - when assignment is not acceptable, we tell the
computer that the assignment OK, even though the
data precision is lost - (variable-type) expression // general format for
casting - int k (int) 1.5 // k 1 fractional part
truncated - char c 'A'
- short s (short) c // assigning a char type
value to a short // variable or vice versa
needs casting. - char c (char) -1 // c 65535
- Note that 1111 1111 1111 11112 is -1 for signed
integral type (in two's complement notation, the
leftmost bit is a sign bit) which is 6553510 for
unsigned integral type - short s (short) 100000 // s -31072
- // 10000010 1 1000 0110 1010 00002
- // the high bit is dropped
47F) Class packages
- provides a more systematic way to organize class
names - instead of having several class definitions for
different staff types, like HRStaff, EDPStaff,
AccountStaff, etc., we can have one Staff class
to belong to hr, edp and account packages. - The fully qualified names for the staff classes
will then be hr.Staff, edp.Staff and
account.Staff. - In each Java source file ( .java file), use
package declaration to indicate the package to
which the class definition belongs - at most one package declaration
- must be the first statement in the source file
- package hr
- class Staff ...
- the file names of the above hr.Staff, edp.Staff
and account.Staff are all Staff.java.
48- So, we create subdirectories hr, edp and account
and store the Java source files in them
accordingly - to create an object based on the class
account.Staff - account.Staff staff new account.Staff()
- If our program refers to the account.Staff class
frequently, writing such a long class name can be
tedious. - To prevent our program from requiring lengthy
class names, we can place an import declaration
in our source file as - import account.Staff // or import account.
- Then, anywhere in our program, wherever we refer
to the class name, Staff, it is the
account.Staff. - Staff s new Staff()
- As a summary, the layout of a Java program must
be - package-declaration
- import-declarations
- class-definitions
49G) Class members
- In some cases, all objects of the same class
share the same attribute. - eg., all accounts in the same bank share the same
interest rate. - instead of having an instance variable
interestRate for each object, use a single
attribute interest to be shared by all objects. - Such shared attributes are known as class
variables. - The keyword static is used to define class
members. - For example,
- // The class definition of an account
- class Account
- static double interestRate // Common interest
rate - double balance // Account balance
- // To calculate the interest
- double calculateInterest()
- return balance interestRate
-
50Account class
InterestRate
Account object 1
balance
calculateInterest() return
interestRate
balance
balance
interestRate
balance
51class method
- Similar to class variables, it is possible to use
a class method without creating an object of the
class. Therefore, we can have the following
expression -
- A special class method named main() is crucial to
Java application. The definition of the method
is
// The class definition of a simple
calculator class Calculator // To calculate
the circle circumference public static double
calculateCircumference(double r) return 2.0
3.1415 r
double c Calculator.calculateCircumference(2.0)
public static void main ( String args ) . . .
. . .
52Instance members vs. Class members
Instance members Class members
Declaration non-static static
Associated with An object of the class (for instance variables, each object has its own copy). The class itself (all objects of the same class share the same class variable).
Available since The creation of an object. The class definition is loaded into the JVM(without the necessity of creating an object of the class)
Access via A reference variable of the class type Usually the class name
Accessibility Accessible by instance methods only. Accessible by both instance and class methods.
53- instance methods can access both instance and
class members, whereas class methods can only
access class members. - eg, the class variable, INTEREST_RATE, of the
class Bank can be accessed by - double rate Bank.INTEREST_RATE // better
- or
- Bank b new Bank()
- double rate b.INTEREST_RATE //
- The former convention is preferable.
- it is shorter,
- it tells us that the variable INTEREST_RATE is
associated with the class Bank, - instead of with a particular object of the class
Bank as in the latter one
54Remarks
- static, together with the keyword final, can be
used to mark a variable to be constant, so that
the content of the variable is always available
and cannot be changed. - // constant variable is usually in uppercase
- public static final double INTEREST_RATE 5.0
- Math.PI, Math.E (the base of the natural
logarithms) - Actually, a class definition in the JVM can be
considered an object. - This object is created automatically when the JVM
loads the class definition from the corresponding
class file. - difference between a usual object and class
object is - there must be only one class object for a class
definition - a single class definition can create more than
one objects