[5] Programming Language Fundamentals (Part 2)
[5] Programming Language Fundamentals (Part 2)
LANGUAGE
FUNDAMENTALS
1
2 DEFINING YOUR OWN
CLASSES
WHY PROGRAMMER-
DEFINED CLASSES?
Using just the String, GregorianCalendar,
JFrame and other standard classes will not
meet all of our needs. We need to be able to
define our own classes customized for our
applications.
Learning how to define our own classes is the
first step toward mastering the skills necessary
in building large programs.
Classes we define ourselves are called
programmer-defined classes.
3
EXAMPLE 1: USING THE
Bicycle CLASS
class BicycleRegistration {
public static void main(String[] args) {
Bicycle bike1, bike2;
String owner1, owner2;
: Bicycle : Bicycle
bike1 = new Bicycle( );
bike1.setOwnerName("Adam Smith");
ownerName ownerName
Sample Code
6
THE PROGRAM STRUCTURE
AND SOURCE FILES
BicycleRegistration Bicycle
There
Therearearetwo
twosource
source
files. Each class
files. Each class
definition
definitionisisstored
storedin
inaa
BicycleRegistration.java Bicycle.java separate
separatefile.
file.
Bicycle( )
Method
MethodListing
Listing
We
We list the nameand
list the name andthe
the
getOwnerName( )
data type of an
data type of an
argument
argumentpassed
passedtotothe
the
setOwnerName(String) method.
method.
TEMPLATE FOR CLASS
DEFINITION
Import
Import
Statements
Statements
Class
ClassComment
Comment
class { Class
ClassName
Name
Data
DataMembers
Members
Methods
Methods
(incl.
(incl.Constructor)
Constructor)
}
DATA MEMBER
DECLARATION
<modifiers> <data type> <name> ;
Modifier
Modifier Data
Data Type
Type Name
Name
ss
private String
ownerName ;
Note:
Note:There’s
There’sonly
onlyone
onemodifier
modifierin
inthis
this
example.
example.
METHOD DECLARATION
<modifier> <return type> <method name> ( <parameters> ){
<statements>
}
Modifie
Modifie Return
Return Method
Method Parameter
Parameter
rr Type
Type Name
Name
public Bicycle ( ) {
ownerName = "Unassigned";
}
Statements
Statements
EXAMPLE 2: USING Bicycle
AND Account
class SecondMain {
//This sample program uses both the Bicycle and Account classes
public static void main(String[] args) {
Bicycle bike;
Account acct;
String myName = "Jon Java";
bike = new Bicycle( );
bike.setOwnerName(myName);
acct = new Account( );
acct.setOwnerName(myName);
acct.setInitialBalance(250.00);
acct.add(25.00);
acct.deduct(50);
//Output some information
System.out.println(bike.getOwnerName() + " owns a bicycle and");
System.out.println("has $ " + acct.getCurrentBalance() +
" left in the bank");
}
}
THE Account CLASS
class Account {
private String ownerName; public void setInitialBalance
(double bal) {
private double balance;
balance = bal;
public Account( ) { }
ownerName = "Unassigned";
balance = 0.0; public void setOwnerName
} (String name) {
public void add(double amt) { ownerName = name;
balance = balance + amt; }
} }
public void deduct(double amt) {
balance = balance - amt;
}
public double getCurrentBalance( ) {
return balance;
}
public String getOwnerName( ) {
return ownerName;
}
Page 1 Page 2
THE PROGRAM STRUCTURE
FOR SecondMain Bicycle
SecondMain
Account
20 x 20.0
Values of
arguments are
Passing Side Receiving Side passed into
memory
Literal constant
has no name
allocated for
parameters.
PASSING OBJECTS TO A
METHOD
As we can pass int and double values, we can
also pass an object to a method.
When we pass an object, we are actually
passing the reference (name) of an object.
− It means a duplicate of an object is NOT
created in the called method.
19
PASSING A Student OBJECT
1
LibraryCard card2; student st
card2 = new LibraryCard();
card2.setOwner(student);
card2
Passing Side 1
class LibraryCard {
private Student owner;
2
public void setOwner(Student st) {
}
owner = st;
2 :
LibraryCard
:
Student
}
owner name
Receiving Side “Jon Java”
borrowCnt email
1 Argument is passed 0 “jj@javauniv.ed
u”
2 Value is assigned to the
data member State of Memory 20
SHARING AN OBJECT
21
INFORMATION HIDING AND
VISIBILITY MODIFIERS
The modifiers public and private designate
the accessibility of data members and methods.
If a class component (data member or method)
is declared private, client classes cannot access
it.
If a class component is declared public, client
classes can access it.
Internal details of a class are declared private
and hidden from the clients. This is
information hiding.
22
ACCESSIBILITY EXAMPLE
… class Service {
public int memberOne;
Service obj = new Service();
private int memberTwo;
public void doOne() {
obj.memberOne = 10;
…
obj.memberTwo = 20; }
private void doTwo() {
obj.doOne(); …
}
obj.doTwo(); }
…
Client Service 23
DATA MEMBERS SHOULD BE
PRIVATE
Data members are the implementation details
of the class, so they should be invisible to the
clients. Declare them private .
Exception: Constants can (should) be declared
public if they are meant to be used directly by
the outside methods.
24
GUIDELINE FOR VISIBILITY
MODIFIERS
Guidelines in determining the visibility of data
members and methods:
Declare the class and instance variables
private.
Declare the class and instance methods
private if they are used only by the other
methods in the same class.
Declare the class constants public if you want
to make their values directly readable by the
client programs. If the class constants are
used for internal purposes only, then declare
them private.
25
DIAGRAM NOTATION FOR
VISIBILITY
26
CLASS CONSTANTS
We illustrate the use of constants in
programmer-defined service classes here.
Remember, the use of constants
− provides a meaningful description of what the
values stand for. number = UNDEFINED; is more
meaningful than number = -1;
− provides easier program maintenance. We only
need to change the value in the constant
declaration instead of locating all occurrences of
the same value in the program code
27
A SAMPLE USE OF
CONSTANTS
import java.util.Random;
class Die {
public Dice( ) {
random = new Random();
number = NO_NUMBER;
}
return result;
}
29
LOCAL, PARAMETER, AND
DATA MEMBER
An identifier appearing inside a method can be
a local variable, a parameter, or a data
member.
The rules are:
− If there’s a matching local variable declaration or
a parameter, then the identifier refers to the local
variable or the parameter.
− Otherwise, if there’s a matching data member
declaration, then the identifier refers to the data
member.
− Otherwise, it is an error because there’s no
matching declaration.
30
SAMPLE MATCHING
class MusicCD {
String ident;
artist = name1;
title = name2;
title.substring(0,9);
id = ident;
}
31
...
}
CALLING METHODS OF THE
SAME
CLASS
So far, we have been calling a method of
another class (object).
It is possible to call method of a class from
another method of the same class.
− in this case, we simply refer to a method without
dot notation
32
CHANGING ANY CLASS TO A
MAIN
CLASS
Any class can be set to be a main class.
All you have to do is to include the main
method.
class Bicycle {
Bicycle myBike;
33
34 SELECTION
STATEMENTS
THE if STATEMENT
int testScore;
This
Thisstatement
statementisis
System.out.println("You did pass" ); executed
executedififthe
the
testScore
testScore is 70or
is 70 or
higher.
higher.
SYNTAX FOR THE if
STATEMENT
if ( <boolean expression> )
<then block>
else
Boolean
Boolean
<else block>
Expression
Expression
if ( testScore < 70 )
Then
Then System.out.println("You did not pass");
Block
Block
else
Else
Else Block
Block System.out.println("You did pass ");
CONTROL FLOW
false testScore
true
testScore
<70
<70??
System.out.println
System.out.println System.out.println
System.out.println
("You
("Youdid
didpass");
pass"); ("You
("Youdid
didnot
notpass");
pass");
RELATIONAL OPERATORS
< //less than
<= //less than or equal to
== //equal to
!= //not equal to
> //greater than
>= //greater than or equal to
testScore < 80
testScore * 2 >= 350
30 < w / (h * h)
x + y != 2 * (a + b)
2 * Math.PI * radius <= 359.99
COMPOUND STATEMENTS
Use braces if the <then> or <else> block has
multiple statements.
if (testScore < 70)
{
System.out.println("You did not pass“ ); Then
Then
System.out.println(“Try harder next time“ ); Block
Block
}
else
{
System.out.println(“You did pass“ );
System.out.println(“Keep up the good work“ ); Else
Else Block
Block
}
39
STYLE GUIDE
if ( <boolean expression> ) {
…
} else {
… Style
Style 11
}
if ( <boolean expression> )
{
…
} Style
Style 22
else
{
…
}
THE if-then BLOCK
if ( <boolean expression> )
<then block>
Boolean
Boolean
Expression
Expression
if ( testScore >= 95 )
testScore
true
testScore
>=95?
>=95?
System.out.println
System.out.println((
"You
"Youare
arean
anhonor
honorstudent");
false student");
THE NESTED if STATEMENT
The then and else block of an if statement can
contain any valid statements, including other if
statements. An if statement containing another
if statement is called a nested-if statement.
System.out.printl
System.out.printl System.out.println
nn System.out.println
("You
("Youdid
didaagreat
greatjob");
job");
("You
("Youdid
didpass");
pass");
WRITING A PROPER if
CONTROL
if (num1 < 0) negativeCount = 0;
if (num2 < 0)
if (num3 < 0)
negativeCount = 3; if (num1 < 0)
else negativeCount++;
negativeCount = 2;
if (num2 < 0)
else
if (num3 < 0)
negativeCount++;
negativeCount = 2; if (num3 < 0)
else negativeCount++;
negativeCount = 1;
else
if (num2 < 0)
if (num3 < 0)
negativeCount = 2;
else
negativeCount = 1;
The
Thestatement
statement
else
if (num3 < 0)
negativeCount = 1;
negativeCount++;
negativeCount++;
else
negativeCount = 0; increments
incrementsthe
thevariable
variableby
by
one
one
if-else-if CONTROL
if (score >= 90)
System.out.print("Your grade is A");
score 60 F else
System.out.print("Your grade is F");
MATCHING else
Are A
A and B
B different?
if (x < y) A
A Both A
A and B
B means…
if (x < z)
System.out.print("Hello"); if (x < y) {
else if (x < z) {
System.out.print("Good bye"); System.out.print("Hello");
} else {
System.out.print("Good
bye");
}
if (x < y) B
B }
if (x < z)
System.out.print("Hello");
else
System.out.print("Good bye");
BOOLEAN OPERATORS
A boolean operator takes boolean values as
its operands and returns a boolean value.
The three boolean operators are
− and: &&
− or: ||
− not !
P Q P && P || Q !P
Q
false false false false true
false true false true true
true false false true false
true true true true false
DE MORGAN’S LAW
De Morgan's Law allows us to rewrite boolean
expressions in different ways:
if (isValid(30)) {
…
Can be used as } else {
…
}
COMPARING OBJECTS
With primitive data types, we have only one
way to compare them, but with objects
(reference data type), we have two ways to
compare them.
1. We can test whether two variables point to
the same object (use ==), or
2. We can test whether two distinct objects
have the same contents.
USING == WITH OBJECTS
(SAMPLE 1)
String str1 = new String("Java");
String str2 = new String("Java");
if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
if (str1.equals(str2)) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
} false
true
NN
xx==30;
30;
==3
==3??
false
switch WITH break
STATEMENTS
true
NN
switch ( N ) { ==1 xx==10;
10;
==1??
case 1: x = 10;
false break;
break;
break; true
case 2: x = 20; NN
==2 xx==20;
20;
==2??
break;
case 3: x = 30; false break;
break;
true
break; NN
==3 xx==30;
30;
} ==3??
false break;
break;
switch WITH THE default
BLOCK
switch (ranking) {
case 10:
case 9:
case 8: System.out.print("Master");
break;
case 7:
case 6: System.out.print("Journeyman");
break;
case 5:
case 4: System.out.print("Apprentice");
break;
}
SYNTAX FOR THE while
STATEMENT
while ( <boolean expression> )
<statement>
Boolean
Boolean
Expression
Expression
Statemen
Statemen sum = sum + number;
tt
(loop
(loop number = number + 1;
body)
body)
}
CONTROL FLOW OF while
int
intsum
sum==0,
0,number
number==11
number
number<=
<=100
100
true
??
false sum
sum=
=sum
sum+
+
number;
number;
number
number==number
number++
1;
1;
MORE EXAMPLES
Keeps
Keepsadding
addingthe
11 int sum = 0, number = 1; numbers
the
numbers 1, 2, 3,…
1, 2, 3, …
until the sum
until the sum
while ( sum <= 1000000 ) { becomes
becomeslarger
largerthan
than
sum = sum + number; 1,000,000.
1,000,000.
number = number + 1;
}
System.out.println(
"An invalid age was entered. Please try again.");
age = scanner.nextInt( );
}
USEFUL SHORTHAND
OPERATORS
sum = sum + number; is equivalent sum +=
to number;
Infinite
Infinite Loops
Loops
Both
Bothloops
loopswill
willnot
not
terminate because
terminate because
the
theboolean
boolean
22 int count = 1; expressions
expressionswill
never
will
never becomefalse.
become false.
while ( count != 10 ) {
count = count + 2;
}
OVERFLOW
An infinite loop often results in an overflow
error.
An overflow error occurs when you attempt to
assign a value larger than the maximum value
the variable can hold.
In Java, an overflow does not cause program
termination. With types float and double, a
value that represents infinity is assigned to the
variable. With type int, the value “wraps
around” and becomes a negative value.
LOOP PITFALL - 2
11 float count = 0.0f;
11
LOOP PITFALL – 3
Goal: Execute the loop body 10 times.
11 count = 1; 22 count = 1;
while ( count < 10 ){ while ( count <= 10 ){
. . . . . .
count++; count++;
} }
33 count = 0; 44 count = 0;
while ( count <= 10 ){ while ( count < 10 ){
. . . . . .
count++; count++;
} }
do {
do {
Statemen
Statemen
sum += number; tt
number++; (loop
(loop
body)
body)
} while ( sum <=
1000000 );
Boolean
Boolean
Expression
Expression
CONTROL FLOW OF do-
while
int
intsum
sum==0,
0,number
number==11
sum
sum+=
+=number;
number;
number++;
number++;
sum
sum<=
<=
true
1000000
1000000??
false
LOOP-AND-A-HALF
REPETITION
CONTROL
Loop-and-a-half repetition control can be
used to test a loop’s terminating condition in
the middle of the loop body.
while (true){
System.out.print("Your name“);
name = scanner.next( );
System.out.println("Invalid Entry." +
"You must enter at least one character.");
}
PITFALLS FOR LOOP-AND-A-
HALF
CONTROL
Be aware of two concerns when using the loop-
and-a-half control:
− The danger of an infinite loop. The
boolean expression of the while statement is
true, which will always evaluate to true. If we
forget to include an if statement to break out
of the loop, it will result in an infinite loop.
number = scanner.nextInt( );
sum += number;
These
Thesestatements
statementsare are
executed for 20 times
executed for 20 times
((i i==0,
0,1,
1,2,
2,……, ,19).
19).
SYNTAX FOR THE for
STATEMENT
for ( <initialization>; <boolean expression>; <increment> )
<statement>
Initializatio
Initializatio Boolean
Boolean Increment
Increment
nn Expression
Expression
ii <
< 20
20 ??
false
true
number
number =
=......;;
sum
sum +=
+=number;
number;
ii ++;
++;
MORE for LOOP EXAMPLES
11 for (int i = 0; i < 100; i += 5)
ii =
= 0,
0, 5,
5, 10,
10, …
… ,,
95
95
is equivalent to
System.out.format("%6d", 498);
CONTROL STRINGS
Integers
% <field width> d
Real Numbers
% <field width> . <decimal places> f
Strings
%s
long elapsedTimeInMilliSec =
endTime.getTime() – startTime.getTime();