Understanding class
definitions
Looking inside classes
5.0
2
Main concepts to be covered
• fields
• constructors
• methods
• parameters
• assignment statements
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
3
Ticket machines – an external
view
• Exploring the behavior of a typical
ticket machine.
– Use the naive-ticket-machine project.
– Machines supply tickets of a fixed price.
• How is that price determined?
– How is ‘money’ entered into a machine?
– How does a machine keep track of the
money that is entered?
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
4
Ticket machines
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Demo
5
Ticket machines – an internal
view
• Interacting with an object gives us
clues about its behavior.
• Looking inside allows us to determine
how that behavior is provided or
implemented.
• All Java classes have a similar-looking
internal view.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
6
Fields, constructor, method
• Fields  store data for each object
to use
• Constructor  allow each object to
be set up
• Methods  implement the behavior
of the object
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
7Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
8
Basic class structure
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public class TicketMachine
{
Inner part omitted.
}
public class ClassName
{
Fields
Constructors
Methods
}
The outer wrapper
of TicketMachine
The inner
contents of a
class
9
Keywords
• Words with a special meaning in the
language:
– public
– class
– private
– int
• Also known as reserved words.
10
Fields/medan/keadaan
• Fields menyimpan nilai
dari suatu objek.
• Dikenal juga sebagai
instance variables
karena nilai yang
disimpan fields
beragam tiap waktu.
• Pd BlueJ, gunakan
pilihan Inspect utk
menampilkan field dr
suatu objek.
• Fields mendefinisikan
keadaan suatu objek.
public class TicketMachine
{
private int price;
private int balance;
private int total;
Constructor and methods omitted.
}
private int price;
visibility modifier type variable name
11Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
12
Constructors
• Method Constructors
menginisialisasi suatu
objek.
• Namanya haruslah sama
dengan nama class.
• Menyimpan nilai awal dari
field.
• Bisa saja memiliki
eksternal parameter untuk
memberi nilai awal pada
field.
• Constructor have a special
role to fulfill, its
responsibility to put each
object of class
public TicketMachine(int ticketCost)
{
price = ticketCost;
balance = 0;
total = 0;
}
13
Passing data via parameters
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Parameters are another
sort of variable.
14Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
15
Assignment
• Suatu nilai disimpan dalam field (dan
variabel lainnya) via assignment
statements:
– variable = expression;
– price = ticketCost;
• Satu variabel menyimpan satu nilai,
jadi nilai sebelumnya akan hilang.
16
Choosing variable names
• There is a lot of freedom over choice
of names. Use it wisely!
• Choose expressive names to make
code easier to understand:
– price, amount, name, age, etc.
• Avoid single-letter or cryptic names:
– w, t5, xyz123
17
Methods
• Suatu Method merupakan implementasi perilaku
dari objek.
• Secara umum ada 3:
– Method constructor: digunakan untuk mencipta
objek dan memberi nilai awal pada objek yang
dicipta
– Method accessor
– Method mutator
• Struktur method terdiri dari bagian header dan
body.
• TicketMachine has four methods:
– getPrice, getBalance, insertMoney, printTicket
18
Method structure
• The header provides the method’s
signature:
– public int getPrice()
• The header tells us:
– the name of the method
– what parameters it takes
– whether it returns a result
– its visibility to objects of other classes
• The body encloses the method’s
statements.
19
Accessor methods
• Method Accessors: mengembalikan informasi
mengenai objek.
• Bagian header mendefinisikan method’s
signature. public int getPrice()
• Bagian body melingkupi semua method’s
statements.
• Terdapat statement return pada body.
20
Accessor (get) methods
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public int getPrice()
{
return price;
}
return type
method name
parameter list
(empty)
start and end of method body (block)
return statement
visibility modifier
22
Test
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public class CokeMachine
{
private price;
public CokeMachine()
{
price = 300
}
public int getPrice
{
return Price;
}
}
;
()
int
-
• What is
wrong
here?
(there are five
errors!)
23
Mutator methods
• Struktur method yang sama: header dan
body.
• Digunakan untuk mengubah keadaan suatu
objek.
• Dengan cara mengubah nilai satu atau
lebih field.
– Umumnya mengandung assignment statements.
– Umumnya menerima parameters.
24
Mutator methods
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public void insertMoney(int amount)
{
balance = balance + amount;
}
return type
method name parameter
visibility modifier
assignment statementfield being mutated
25
set mutator methods
• Fields often have dedicated set
mutator methods.
• These have a simple, distinctive
form:
– void return type
– method name related to the field name
– single parameter, with the same type as
the type of the field
– a single assignment statement
26
A typical set method
public void setDiscount(int amount)
{
discount = amount;
}
We can infer that discount
is a field of type int, i.e:
private int discount;
27Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
28
Protective mutators
• A set method does not have to assign
the parameter to the field.
• The parameter may be checked for
validity and rejected if
inappropriate.
• Mutators thereby protect fields.
• Mutators support encapsulation.
29
Printing from methods
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
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;
}
30Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
31
String concatenation
• 4 + 5
9
• "wind" + "ow"
"window"
• "Result: " + 6
"Result: 6"
• "# " + price + " cents"
"# 500 cents"
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
overloading
32
Quiz
• System.out.println(5 + 6 + "hello");
• System.out.println("hello" + 5 + 6);
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
11hello
hello56
33
Method summary
• Methods implement all object behavior.
• A method has a name and a return type.
– The return-type may be void.
– A non-void return type means the method will
return a value to its caller.
• A method might take parameters.
– Parameters bring values in from outside for the
method to use.
34
Lihat kembali mesin tiket yang
dibuat
• Beberapa perilaku masih kurang sesuai
seperti:
– Tiada pengecekan nilai uang yang masuk.
– Tiada kembalian.
– Tiada pengecekan initialization yg masuk
akal.
• Cara memperbaiki?
– Perlu perilaku yang lebih bagus dan pintar.
35
Making choices in everyday life
• If I have enough money left, then I
will go out for a meal
• otherwise I will stay home and watch
a movie.
36
Making a choice in everyday life
if(I have enough money left) {
go out for a meal;
}
else {
stay home and watch a movie;
}
37
Making choices in Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
if(perform some test) {
Do these statements if the test gave a true result
}
else {
Do these statements if the test gave a false result
}
‘if’ keyword
boolean condition to be tested
actions if condition is true
actions if condition is false
‘else’ keyword
38
Making a choice in the
ticket machine
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public void insertMoney(int amount)
{
if(amount > 0) {
balance = balance + amount;
}
else {
System.out.println(
"Use a positive amount: " +
amount);
}
}
39
Making for loops in Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
for(initialize;perform some test;update) {
Do these statements if the test gave a true result
}
‘for’ keyword
test variable
actions if condition is true
update variableInitialize variable
40
Writing a for loop
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
int i;
int sum=0;
for(i=0;i<10;i++) {
sum = sum + i;
}
41
Review
• Class terdiri dari fields, constructors
dan methods.
• Fields menyimpan nilai yang
menentukan keadaan suatu objek.
• Constructors mencipta objek.
• Methods memberikan implementasi
perilaku dari objek.
42
Review
• Fields, parameters dan variabel lokal,
semuanya merupakan variabel.
• Fields ‘hidup’ selama objek tersebut
hidup.
• Parameters digunakan untuk menerima
nilai pada constructor atau method.
• Variabel lokal digunakan sebagai tempat
penyimpanan sementara.
43
Review
• Objects dpt memiliki pilihan via
conditional (if) statements.
• A true or false test memungkinkan
hanya satu aksi yang dipilih dari
beberapa alternatif pilihan.
44
Review (2)
• Fields, parameters and local variables
are all variables.
• Fields persist for the lifetime of an
object.
• Parameters are used to receive values
into a constructor or method.
• Local variables are used for short-lived
temporary storage.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
45
Review (3)
• Methods have a return type.
• void methods do not return anything.
• non-void methods return a value.
• non-void methods have a return
statement.

3 class definition

  • 1.
  • 2.
    2 Main concepts tobe covered • fields • constructors • methods • parameters • assignment statements Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 3.
    3 Ticket machines –an external view • Exploring the behavior of a typical ticket machine. – Use the naive-ticket-machine project. – Machines supply tickets of a fixed price. • How is that price determined? – How is ‘money’ entered into a machine? – How does a machine keep track of the money that is entered? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 4.
    4 Ticket machines Objects Firstwith Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Demo
  • 5.
    5 Ticket machines –an internal view • Interacting with an object gives us clues about its behavior. • Looking inside allows us to determine how that behavior is provided or implemented. • All Java classes have a similar-looking internal view. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 6.
    6 Fields, constructor, method •Fields  store data for each object to use • Constructor  allow each object to be set up • Methods  implement the behavior of the object Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 7.
    7Objects First withJava - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 8.
    8 Basic class structure ObjectsFirst with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class TicketMachine { Inner part omitted. } public class ClassName { Fields Constructors Methods } The outer wrapper of TicketMachine The inner contents of a class
  • 9.
    9 Keywords • Words witha special meaning in the language: – public – class – private – int • Also known as reserved words.
  • 10.
    10 Fields/medan/keadaan • Fields menyimpannilai dari suatu objek. • Dikenal juga sebagai instance variables karena nilai yang disimpan fields beragam tiap waktu. • Pd BlueJ, gunakan pilihan Inspect utk menampilkan field dr suatu objek. • Fields mendefinisikan keadaan suatu objek. public class TicketMachine { private int price; private int balance; private int total; Constructor and methods omitted. } private int price; visibility modifier type variable name
  • 11.
    11Objects First withJava - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 12.
    12 Constructors • Method Constructors menginisialisasisuatu objek. • Namanya haruslah sama dengan nama class. • Menyimpan nilai awal dari field. • Bisa saja memiliki eksternal parameter untuk memberi nilai awal pada field. • Constructor have a special role to fulfill, its responsibility to put each object of class public TicketMachine(int ticketCost) { price = ticketCost; balance = 0; total = 0; }
  • 13.
    13 Passing data viaparameters Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Parameters are another sort of variable.
  • 14.
    14Objects First withJava - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 15.
    15 Assignment • Suatu nilaidisimpan dalam field (dan variabel lainnya) via assignment statements: – variable = expression; – price = ticketCost; • Satu variabel menyimpan satu nilai, jadi nilai sebelumnya akan hilang.
  • 16.
    16 Choosing variable names •There is a lot of freedom over choice of names. Use it wisely! • Choose expressive names to make code easier to understand: – price, amount, name, age, etc. • Avoid single-letter or cryptic names: – w, t5, xyz123
  • 17.
    17 Methods • Suatu Methodmerupakan implementasi perilaku dari objek. • Secara umum ada 3: – Method constructor: digunakan untuk mencipta objek dan memberi nilai awal pada objek yang dicipta – Method accessor – Method mutator • Struktur method terdiri dari bagian header dan body. • TicketMachine has four methods: – getPrice, getBalance, insertMoney, printTicket
  • 18.
    18 Method structure • Theheader provides the method’s signature: – public int getPrice() • The header tells us: – the name of the method – what parameters it takes – whether it returns a result – its visibility to objects of other classes • The body encloses the method’s statements.
  • 19.
    19 Accessor methods • MethodAccessors: mengembalikan informasi mengenai objek. • Bagian header mendefinisikan method’s signature. public int getPrice() • Bagian body melingkupi semua method’s statements. • Terdapat statement return pada body.
  • 20.
    20 Accessor (get) methods ObjectsFirst with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public int getPrice() { return price; } return type method name parameter list (empty) start and end of method body (block) return statement visibility modifier
  • 21.
    22 Test Objects First withJava - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class CokeMachine { private price; public CokeMachine() { price = 300 } public int getPrice { return Price; } } ; () int - • What is wrong here? (there are five errors!)
  • 22.
    23 Mutator methods • Strukturmethod yang sama: header dan body. • Digunakan untuk mengubah keadaan suatu objek. • Dengan cara mengubah nilai satu atau lebih field. – Umumnya mengandung assignment statements. – Umumnya menerima parameters.
  • 23.
    24 Mutator methods Objects Firstwith Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public void insertMoney(int amount) { balance = balance + amount; } return type method name parameter visibility modifier assignment statementfield being mutated
  • 24.
    25 set mutator methods •Fields often have dedicated set mutator methods. • These have a simple, distinctive form: – void return type – method name related to the field name – single parameter, with the same type as the type of the field – a single assignment statement
  • 25.
    26 A typical setmethod public void setDiscount(int amount) { discount = amount; } We can infer that discount is a field of type int, i.e: private int discount;
  • 26.
    27Objects First withJava - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 27.
    28 Protective mutators • Aset method does not have to assign the parameter to the field. • The parameter may be checked for validity and rejected if inappropriate. • Mutators thereby protect fields. • Mutators support encapsulation.
  • 28.
    29 Printing from methods ObjectsFirst with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 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; }
  • 29.
    30Objects First withJava - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 30.
    31 String concatenation • 4+ 5 9 • "wind" + "ow" "window" • "Result: " + 6 "Result: 6" • "# " + price + " cents" "# 500 cents" Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling overloading
  • 31.
    32 Quiz • System.out.println(5 +6 + "hello"); • System.out.println("hello" + 5 + 6); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 11hello hello56
  • 32.
    33 Method summary • Methodsimplement all object behavior. • A method has a name and a return type. – The return-type may be void. – A non-void return type means the method will return a value to its caller. • A method might take parameters. – Parameters bring values in from outside for the method to use.
  • 33.
    34 Lihat kembali mesintiket yang dibuat • Beberapa perilaku masih kurang sesuai seperti: – Tiada pengecekan nilai uang yang masuk. – Tiada kembalian. – Tiada pengecekan initialization yg masuk akal. • Cara memperbaiki? – Perlu perilaku yang lebih bagus dan pintar.
  • 34.
    35 Making choices ineveryday life • If I have enough money left, then I will go out for a meal • otherwise I will stay home and watch a movie.
  • 35.
    36 Making a choicein everyday life if(I have enough money left) { go out for a meal; } else { stay home and watch a movie; }
  • 36.
    37 Making choices inJava Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling if(perform some test) { Do these statements if the test gave a true result } else { Do these statements if the test gave a false result } ‘if’ keyword boolean condition to be tested actions if condition is true actions if condition is false ‘else’ keyword
  • 37.
    38 Making a choicein the ticket machine Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public void insertMoney(int amount) { if(amount > 0) { balance = balance + amount; } else { System.out.println( "Use a positive amount: " + amount); } }
  • 38.
    39 Making for loopsin Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling for(initialize;perform some test;update) { Do these statements if the test gave a true result } ‘for’ keyword test variable actions if condition is true update variableInitialize variable
  • 39.
    40 Writing a forloop Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling int i; int sum=0; for(i=0;i<10;i++) { sum = sum + i; }
  • 40.
    41 Review • Class terdiridari fields, constructors dan methods. • Fields menyimpan nilai yang menentukan keadaan suatu objek. • Constructors mencipta objek. • Methods memberikan implementasi perilaku dari objek.
  • 41.
    42 Review • Fields, parametersdan variabel lokal, semuanya merupakan variabel. • Fields ‘hidup’ selama objek tersebut hidup. • Parameters digunakan untuk menerima nilai pada constructor atau method. • Variabel lokal digunakan sebagai tempat penyimpanan sementara.
  • 42.
    43 Review • Objects dptmemiliki pilihan via conditional (if) statements. • A true or false test memungkinkan hanya satu aksi yang dipilih dari beberapa alternatif pilihan.
  • 43.
    44 Review (2) • Fields,parameters and local variables are all variables. • Fields persist for the lifetime of an object. • Parameters are used to receive values into a constructor or method. • Local variables are used for short-lived temporary storage. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 44.
    45 Review (3) • Methodshave a return type. • void methods do not return anything. • non-void methods return a value. • non-void methods have a return statement.