Download Method - Department of Computer Science and Information Systems

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
SOFTWARE AND PROGRAMMING 1
Lecture: MB33
7:30-9:00 (except 11&18.01.06)
Lab: B43, MB321, MB536
6:00-7:30 (from 25.01.05)
[each student must have obtained access to Birkbeck computing]
SORRY; Rooms and allocations are wrong here; please
consult first slide in Lecture 3!- B.M. 25/1/6
Lab MB321: students whose family names fall in A-D
Instructor:
Mrs Jenny Hu
SCSIS, room NG26, tel. 020 7631 6726
E-mail: [email protected]
Lab MB536: students whose family names fall in E-L
Instructor:
Mr Zheng Zhu
LKL, tel. 020 7763 2115
E-mail: [email protected]
Lab B43: students whose family names fall in M-Y
Instructor:
Prof. Boris Mirkin
SCSIS, room 111, tel. 020 7631 6746
E-mail: [email protected]
SOFTWARE AND PROGRAMMING 1
WebCT/Tests/Assignments:
Marie-Helene Ng
SCSIS, room NG26, tel. 0207 631 6550
E-mail: [email protected]
To be able to submit your assignments
you must have sent your CCS username
to Marie-Helene by 31 January
Webpages
The course web page is at
webct.bbk.ac.uk
Please check it regularly. It will be
used for announcements and
assignments.
Another page, at an open-to-all
web-site, will function with
relevant materials too:
www.dcs.bbk.ac.uk/~mirkin/sp105
3
Formerly Recommended Texts
1. David J. Barnes & Michael Kölling
Objects First with Java: A Practical
Introduction
using BlueJ, Second edition,
Pearson Education,
2005, ISBN 0-13-124933-9
The publisher supplies a helpline (team’s telephone
included) in installing the related software
2. J. Farrell
Java Programming, Second edition, Course
Technology, Thompson,
2003, ISBN 0-619-21500-3
3. I. Pohl, C. McDowell
Java by dissection, Addison-Wesley,
2000, ISBN 0201751585
4. Free: ON-LINE text by D. Eck (on my web site) and
other useful URLs
4
New Recommended Text
Q. Charatan, A. Kans
Java in Two Semesters, Second edition, The
McGrow-Hill Education, 2006, ISBN 978-0-07-710889-2
[ Free: ON-LINE text by D. Eck (on my web site) and
other useful URLs]
5
Software is free
• Available on BBK’s network
– Java JDK (which allows you to compile and
execute your program)
– BlueJ (Preferred editor)
• Installing BlueJ (for home use)
– First download the Java JDK from
http://java.sun.com/j2se/1.5.0/download.jsp
– Download BlueJ from
http://www.bluej.org/download/download.html
– Run “bluejsetup-202.exe” and follow the
given instructions
6
Concepts from lecture 1
• Compiler (javac.exe) and Interpreter
(java.exe)
• Class (template) and Object (its
instantiation); every Java program
must be a class
• Variable and its type; primitive types
• Method (input-output operation) and
its Parameters (inputs - with their
types at method’s description)
7
Concepts to be learnt
• Arithmetic expression and
precedence
• Boolean expression
• Statement (a Java instruction)
• Loop for
• Usage in classes for hello-printing
and ticket-vending machine (BlueJ)
8
Objects and classes
• Classes: program templates
– represent all objects of a kind (example:
“student”)
• Objects = instances
– A template copy to represent a specific
element of the class (“an individual
student”)
– Instances are created with the so-called
constructors, explicit in JDK or
somewhat easier in BlueJ
9
Basic class structure
public class TicketMachine
{
Inner part of the class omitted.
}
public class ClassName
{
Variables
Constructors
Methods
}
The outer wrapper
of TicketMachine
The contents of a
class
10
Method
Method in Java is a named set of
instructions that transforms some input
into an output. This is, actually, a
machine implementation of the concept
of algorithm which itself is a
computational analogue to the
mathematical concept of function.
Static method: is shared by all instances.
11
Structure of a method
Output’s type
Inputs
modifiers return-type name ( parameter-list )
{
statements;
return variable/expression;
//if return type is not void
}
Modifiers:
– static method/variable that belongs to class as
whole and is shared by all
– public method/variable that is accessible from
anywhere
– private - method/variable that is accessible from only
12
within the class
Fields
• Fields store values
for an object.
• They are also known
as instance variables.
• Use the Inspect
option to view an
object’s fields.
• Fields define the
state of an object.
public class TicketMachine
{
private int price;
private int balance;
private int total;
Constructor and methods omitted.
}
visibility modifier
type
variable name
private int price;
13
Assigning values
• Values are stored into fields (and other
variables) via assignment statements:
– variable = expression;
– price = ticketCost;
• The value on the right is assigned to a
variable on the left.
• A variable stores a single value, so any
previous value is lost.
14
Variable
• It provides for multiple uses of the same
program
• A variable is a name for a location in
memory that can hold data.
• Variables are declared and initialised
• A variable declaration includes the following:
– A data type that identifies the type of data that is stored in
the variable
– An identifier that is the variable’s name
– An optional assigned initial value
– Semicolon.
15
Scope of a variable:
The range of statements that can access
the variable.
It stretches from the declaration point
to the end of the block containing the
declaration
Q: WHAT is BLOCK ?
Q: WHAT is DECLARATION?
(part within curly braces{…} )
(type name ; 3-part command)
16
Two JAVA environments
• Java Developer Kit JDK (currently, J2SE)
(Conventional)
• Blue J (A public project to make JAVA
coding easier)
– Both available in Birkbeck
17
Conventional JDK: Editing
• A source code can be edited in any
text editor: Notepad, emacs, PFE, ...
• MS Word caveat: by default, Word
does not save in ASCII text format
• Make sure to save the code before
compiling! The file name: the same
as that of the class, with extension:
say, class NicTe{…} must be saved as
file NicTe.java, case sensitive
18
Command line invocation
• compilation and execution of Java in
JDK are done from a command line
• On Microsoft systems: DOS shell
• On Unix: Unix shell
• Must make sure that the commands
for compiler and runtime (JVM) are in
the command path.
19
Compiling with JDK
• Name of the JDK compiler: javac
• To invoke:
javac <source name>
• compiles <source name> and all classes it
depends on into an executable on JVM file
<source name>.class
• Example:
javac NicTe.java
produces file NicTe.class
20
Execution
• “java” starts the Java virtual
machine:
java NicTe
• The named class is loaded and
execution is started.
• Other classes are loaded as needed.
• Only possible if class has been
compiled into a file, say, NicTe.class
21
JDK Problem: Execute what?
How does the system know which
method to execute?
22
The main method in JDK
• The JDK java system always executes a method
called main with a certain signature:
Signature
_______________________
public static void main(String[] args)
{ ...
}
• To work with JDK, such a method must be
present in your program!
23
A simplest program
/* HelloWorld.java
Purpose: printing a message to the screen
*/
class HW {
// Each program is organised as a class
public static void main(String[] args) {
System.out.println("Hello, World!");
}
} // end of class HW
/* Always Three Types of Elements ONLY:
• comments
• class (with modifiers)
• methods (with modifiers and parameters) */
24
BlueJ coding
• BlueJ programs are organised in the
so-called projects
• A BlueJ project is stored in a
directory on disk
• Some files store the source code,
some store the compiled code, some
store additional information.
25
The BlueJ directory structure
project: calculator
Calculator
UserInterface
CalcEngine
c:\bluej\calculator\
bluej.pkg
bluej.pkh
Calculator.java
Calculator.class
Calculator.ctxt
UserInterface.java
UserInterface.class
UserInterface.ctxt
CalcEngine.java
CalcEngine.class
CalcEngine.ctxt
26
The BlueJ file structure
• bluej.pkg - the package file. Contains
information about classes in the package.
One per package.
• bluej.pkh - backup of the package file.
• *.java - standard Java source file (text).
One per class.
• *.class - standard Java code file. One per
class
• *.ctxt - BlueJ context file. Contains extra
information for a class. One per class.
27
BlueJ HelloWorld N times
public class HelloN {
int number;
\\ variable declared
public void go()
{ System.out.println("Hello, world"); }
public HelloN(int howmany)
{number=howmany; } \\constr-r to initialise an object
public void prrt()
\\printing number times
{
for(int i=1;i<=number;i++) \\loop
go();
System.out.println("ok");
}
28
Loop for
for(int var=1;var<=st;var++){do operation
depending on var}
var++ is not
var=var+2;
• Two types of parentheses: () and {}
• The expression in () consists of three different
items: initialising a counting variable, variable
update, and stop-condition
• Given a value of var, stop-condition is checked; if
true, {} is executed, after which var is updated;
if no, the program proceeds further on, after the
block { }
29
No { } in for-loop in HelloN
Why?
Let us add { }: where?
Is there any difference
between before and after “ok”?
30
Arithmetic Operations in Java
• * 53=15
• / 36/9=4, 39/9=4, 39/50=0 (integers)
• / 36.0/9=4.0, 39.0/9=4.33333333,
39.0/50=0.78 (reals)
• % 36%9=0, 39%9=3, 39%50=39
• +
5+3=8
• 5–3=2
• Other operators such as Abs or exp or log
are in class Math of Java (to be explained
later)
31
Arithmetic expressions
• 2*6/4+5– 2*3= 3+5–6=2
(integers)
• 2 * 6.0 / (4 + 5) – 2 * 3 = 12.0/9 – 6 = –
4.67 (reals are here)
• 2 * 6 / 4 + (5 – 2) * 3 = 12
32
Ticket Machine (1)
/* * TicketMachine models a ticket machine that issues
* flat-fare tickets. */
public class TicketMachine{
private int price;
private int balance;
private int total;
public TicketMachine(int ticketCost) //constructor
{ price = ticketCost;
balance = 0;
total = 0; }
public int getPrice()
{
return price; }
public int getBalance()
{ return balance; }
// see next page for continuation
33
Ticket Machine (2)
// TicketMachine’s continuation
public void insertMoney(int amount)
{
if(amount > 0)
balance = balance + amount;
else {
System.out.println("Use a positive amount: " +
amount);
}
}
public int refundBalance()
{ int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
// continued on the next page
34
Ticket Machine (3)
// TicketMachine’s end
public void printTicket()
{
if(balance >= price) {
// Simulate the printing of a ticket.
System.out.println("##################");
System.out.println("# The BlueJ Line");
System.out.println("# Ticket");
System.out.println("# " + price + " pence.");
System.out.println("##################");
System.out.println();
total = total + price; // Update the total
balance = balance - price; // Update the balance
}
else { System.out.println("You must insert at least: " +
(price - balance) + " more pence."); }
}
}//end of class
35
Questions
• How many methods are in TicketMachine?
• If there is any syntactic difference
between a method and constructor?
• Which of the methods are accessors and
which are mutators?
36
Accessor methods
• Accessors provide information about the state
of an object.
• Methods have a structure consisting of a
header and a body.
• The header defines the method’s signature.
public int getPrice()
• The body encloses the method’s statements.
37
Accessor methods
return type
visibility modifier
method name
parameter list
(empty)
public int getPrice()
{
return price;
return statement
}
start and end of method body (block)
38
Mutator methods
• Have a similar method structure: header
and body.
• Used to mutate (i.e. change) an object’s
state.
• Achieved through changing the value of
one or more fields.
– Typically contain assignment statements.
– Typically receive parameters.
39
Mutator methods
visibility modifier return type (void)
method name
parameter
public void insertMoney(int amount)
{
balance = balance + amount;
}
field being changed
assignment statement
40
Printing from methods
public void printTicket()
{
// Simulate the printing of a ticket.
System.out.println("##################");
System.out.println("# The BlueJ Line");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("##################");
System.out.println();
// Update the total collected with the balance.
total = total + balance;
// Clear the balance.
balance = 0;
}
41
Passing data via parameters
42