CSIT111 Lecture 5
CSIT111 Lecture 5
1
What you already know
• How to use the UML class symbol to describe classes
including data fields and methods
• How to use UML class diagrams to describe relationship
between classes
• How to declare and use local variables in methods to
process data
• How static methods of existing classes can be called
(Example: Math class methods)
• How to declare reference variables and objects of
existing classes (Example: Scanner methods)
• How to input values from the command line and the
keyboard input buffer
• How to display values in various formats
2
What you need to know
• How to define a new class in a Java program based upon
its UML description
Storage
-data: int Java ?
+getData()
+setData(int)
3
Limitations of main() method
6
What should methods do?
• When you define a method you need to decide what object behaviour it
will be responsible for
- support user input
- carry out calculations
- set private data fields Object behaviours
- read private data fields
- make decisions
. . .
• Each method must be responsible for one clearly defined task
• Do not define methods which "do everything" as their use will be
confusing and may cause problems if you need to make some changes
Example: double b = Math.cos(f); // calculates cos
Would this method be generic and simple to use if besides calculating cos it
would prompt you to enter a value for f and then start playing music when the
result is returned?
One method – One task
7
Can methods receive input data?
- To complete their tasks, methods may need input data
- Input data can be passed from other methods: parameters (arguments)
class Example {
public static void main(String[] args) main() is a calling method in
{ this example
String message = "Hello";
One input parameter is passed
System.out.println( message ); Nothing needs to be returned back
double x = Math.random();
local variables Body of the method
int rndInt = (int)(x*n) + 1;
return rndInt;
}
return statement
Returns the value and control to the calling method
10
Method return type
return_type methodName( formal parameter list )
{
. . . . .
}
11
Formal parameter list
return_type methodName( formal parameter list )
{
. . .
}
• The list contains parameters that will be assigned with actual values
(passed to the method when it is called).
Parameters in the list are separated by commas.
• Each parameter must have a data type
• If no parameters are passed to the method, use empty brackets ()
Examples:
public int calcAverage( int x1, int x2 )
private double getHeight( double velocity, double theta )
public void prompt( )
12
Parameters and local variables
• Local variables of a method are variables declared
inside the method
• Method parameters and local variables can be used
only in the executable statements inside the method
• Method parameters and local variables must have
unique identifiers
A method Memory space of the method
public int average( int x, int y )
x
{ parameters
y
int avg;
avg = ( x + y )/2; avg a local variable
return avg;
They “exist” only inside this method
}
They can be used only inside this method
13
Quiz
• Find errors in the following definitions
public double multiply( int x, y)
{
int z, x;
z = x*y + z;
return z;
}
sum += x;
return (sum/2.0);
}
14
Formal and Actual parameters
public static void main(String[] args)
{
double price1 = 10.0, price2 = 20.0;
double avgPrice; Actual parameters
/* Method call */ price1 and price2
avgPrice = findAverage( price1 , price2);
. . . . .
Copies ( rvalues) of
} 10.0 20.0 price1 and price2
1. Values of price1 and price2 are copied and the copies are passed to the method
2. Lvalues num1 and num2 are assigned with the passed rvalues
15 3. The result is returned back to main() where it is assigned to lvalue avgPrice
Quiz
These variables
public static int calc(int j, int k) {
a and b are local to
calc(). They int a=0, b = 5; calc() method scope
have this method cV = a; //cV is visible everywhere within the class
scope return ( j+k/b ); // formal parameters j, k
// and local variables a, b
// are visible only localy
}
17 }
Quiz
Will the compiler complain about conflicting identifiers
a and b?
public int method1()
{ Memory space of
int a=5, b=9; method1()
a b
int result = method2( a, b );
return 0;
5 9
}
values passed
18
Identical names
• Local variables of one method cannot have conflicting names with
variables defined in other methods (their scope is limited to a method)
• What if a local variable has the same name as one of the data fields
(a class scope variable) ?
class Example
{ Why static
private static int number, code;
public static void main(String[] args) {
number = 1; // the class scope variable is used
testLocal();
out.println( "main() method: " + number + " " + code);
}
Why static
public static void testLocal() {
int number = 99; // a method scope variable is declared (local)
out.println( "testLocal() method: " + number + " " + code);
}
}
If a local variable has the same name as a class
19 scope variable, the local one has a higher priority
Calling methods (within a class)
• Once a method is defined in a class, it can be called
directly from other methods in the same class
class Example
{ // method definition
public int getSum(int n1, int n2) {
return n1+n1 ;
}
public void printResult() {
int sum = getSum( 2, 17 ); // a call within a class
. . .
} actual parameters
method name
}
20
Calling static methods
• Static methods defined in a class as public can be
called from other classes through the class name
class Example
{ // method definition
public static void printNumber( int n1 ) {
System.out.println(n1);
}
}
class Test {
public void printResult() {
Example.printNumber( 12 ); // a call from another class
}
(3) actual parameter
} (1) class name the dot (2) method name
class Test {
public void printResult() {
Example exVar = new Example(); // an object must be declared
exVar.printNumber( 12 ); // a call from another class
}
the dot (3) actual parameters
} (1) object name (2) method name
1. Declare an object
2. Specify the object name
3. Specify the method name
4. Provide actual input parameters
22
Defining a class with two methods
Example: Example
1. main() - input two double numbers separated by space
2. calculateAverage() is called from main() to calculate the average +main(): void
+calculateAverage(): double
3. main() – print the result returned by calculateAverage()
class Example {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("Input two numbers: ");
double d1 = inp.nextDouble();
double d2 = inp.nextDouble();
double average = calculateAverage( d1, d2 ); // method call
System.out.println("The average is :" + average);
}
Why static
public static double calculateAverage(double v1, double v2) {
double average = (v1 + v2)/2.0;
return average; // this is a locally declared average
}
23
}
Static vs. Constant
Memory Class Example
-static double a=1.0
-static void modify(double b){
a=b;
}
-static void print(double b){
System.out.println(b);}
Objects share the same value in memory. Modifications in objects are allowed, and the
24
result will automatically affect all other objects of the same class.
Static vs. Constant
Memory
Class Example
-final double a=1.0 //constant
-void use(double b){
print(b+a);
}
Object Example1
-a //1.0 Object Example2
Object Example3
-print(a) //1.0 -a //1.0
-a //1.0
-use(2.0) //3.0 -print(a) //1.0
-print(a) //1.0
-a=a+1 ?? -use(3.0) //4.0
-use(4.0) //5.0
Not allowed
contains
AccountSystem StudentAccount
-sName: String
-sEmail: String
+main(): void
-sNumber: int
-printReport():void
+setName(String): void
+getName(): String
+getNumber: int
+getEmail(): String
-createStudentNumber(): void
-createEmail(): void
26
A program with two classes
• It is not a good practice to implement all program components and
then compile and debug it
- you are very likely to end up with many compilation errors
- when you fix one bug there is a chance that you'll introduce a new one
Common solution: Incremental development combined with debugging
- implement the simples possible version that can be compiled
- add elements one-by-one, compile, fix bugs
It's possible (simple to start with) to define two classes in one .java file
File name: AccountSystem.java
class StudentAccount
{
class AccountSystem
{
public static void main(String[] args)
{
}
27 }
A program with two classes
• More details added
class AccountSystem
{
public static void main(String[] args)
{
StudentAccount stud1 = new StudentAccount(); // create an object
String name1 = stud1.getName(); //call a public method to get sName
System.out.println("Student's name: " + name1);
}
}
Student's name: null
28
A program with two classes
import java.util.Scanner; File name: AccountSystem.java
class StudentAccount
{
private String sName;
public String getName() { return sName; }
public void setName(String name) { sName = name; }
}
class AccountSystem
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.print(" Enter a name: ");
String aName = keyboard.next(); // read a word
StudentAccount stud1 = new StudentAccount(); // create an object
stud1.setName( aName ); // call a public method to set sName
String name1 = stud1.getName(); // get a private field
System.out.println("Student's name: " + name1);
29
}
}
this reference variable
• What if a formal parameter of a method has the same identifier as a
class scope variable?
class StudentAccount
{
private String name;
. . .
public void setName(String name) { As the local scope has a higher
name = name; // which name? priority than the class scope,
} the formal parameter name
} will be assigned to itself
class AccountSystem
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.print(" Enter a name: ");
String aName = keyboard.next(); // read a word from the input buffer
StudentAccount stud1 = new StudentAccount(); // create an object
stud1.setName( aName ); // call a public method to set private field sName
String name1 = stud1.getName(); // get a private field via a public method
System.out.println("Student's name: " + name1);
}
31 }
Suggested reading
32