Anda di halaman 1dari 26

Pemrograman Lanjut

PTIIK - 2013
Class, Instance Variable dan Method
Objectives
Mampu mendeklarasikanclass dan menggunakannya untuk
membuat object.
Mampu mendeklarasikanmethods dalamclass (tingkahlaku
class).
Mampu mendeklarasikaninstance variables dalamclass
(atribut class).
Mampu memanggil method pada object untuk menjalankan
algoritma yang ada di dalamnya.
Memahami perbedaanantara instance variables dari class
dan local variables pada method.
Review Class, Object, Instance Variable
Class terdiri dari satuatau lebih method
Method menyelesaikan tugas dalamsuatu
program
Mendeskripsikan mekanisme untuk menyelesaikan
suatupermasalahan
Menyembunyikan dari user tentangkerumitan
(kompleks) permasalahan itu diselesaikan
Method harus dipanggil untuk dapat menjalankan
tugasnya
Review Class, Object, Instance Variable
Class terdiri dari satuatau lebih atribut / properti
Ditunjukkanoleh suatu variabel (instance variables)
Melekat pada object sebagai instance-nya
Deklarasi Class
Setiapdeklarasi class declaration diawali dengan
keyword publ i c
Class harus disimpan dalamfile dengan nama yang
sama dengan class tersebut dan diakhiri dengan ekstensi
. j ava
Keyword publ i c merupakan access modifier
Deklarasi Class meliputi:
Access modifier
Keyword cl ass
Sepasangkurungkurawal buka dan tutup
Declaring more than one publ i c class
in the same file is a compilation error
Deklarasi Method
Keyword publ i c menandakan method dapat
diakses oleh public (diluar class tersebut)
Keyword voi dmenandakan tidak ada tipe
pengembalian nilai
Access modifier, return type, nama method
dan parentheses merupakan komponen header
dari method
Instansiasi Object dari Class
Untuk membuat sebuah objek atau sebuah
instance pada sebuah kelas digunakan operator
new.
Sebagai contoh, membuat instance dari kelas
string :
String str2 = new String(Hello world!);
String str2 = "Hello";
Memanggil Instance dari Method dan
Passing Variabel
Untuk memanggil sebuah instance method,
gunakan format code berikut :
nameOf Obj ect . nameOf Met hod( par amet er s ) ;
St r i ng st r 1 = new St r i ng( " Hel l o" ) ;
char x = st r 1. char At ( 0) ;
St r i ng st r 2 = new St r i ng( " hel l o" ) ;
bool ean r esul t 1 = st r 1. equal s( st r 2) ;
bool ean r esul t 2 = st r 1. equal sI gnor eCase( st r 2) ;
Syst em. out . pr i nt l n( x) ;
Syst em. out . pr i nt l n( r esul t 1) ;
Syst em. out . pr i nt l n( r esul t 2) ;
Memanggil Method Static
Method Static adalah cara yang dapat dipakai tanpa
inisialisasi suatu class (tanpa menggunakan kata kunci
new)
Method static dibedakan dari contohmethod di dalam
suatuclass oleh kata kunci static.
Cl assname. st at i cMet hodName( par ams) ;
Contoh:
/ / mencet ak dat a pada l ayar
Syst em. out . pr i nt l n( Hel l o wor l d) ;
/ / conver t st r i ng menj adi i nt eger
i nt i = I nt eger . par seI nt ( 10) ;
St r i ng hexEqui val ent = I nt eger . t oHexSt r i ng( 10 ) ;
Class GradeBook
1 / / Fi g. 3. 1: GradeBook. j ava
2 / / Cl ass decl arati on wi th one method.
3
4 publ i c cl ass GradeBook
5 {
6 / / di spl ay a wel come message to the GradeBook user
7 publ i c voi d di spl ayMessage( )
8 {
9 System. out. pri ntl n( "Wel come to the Grade Book!" );
10 } / / end method di spl ayMessage
11
12 } / / end cl ass GradeBook

Print line of text to output
Class GradeBookTest
1 / / Fi g. 3. 2: GradeBookTest. j ava
2 / / Create a GradeBook obj ect and cal l i ts di spl ayMessage method.
3
4 publ i c cl ass GradeBookTest
5 {
6 / / mai n method begi ns programexecuti on
7 publ i c stati c voi d mai n( Stri ng args[ ] )
8 {
9 / / create a GradeBook obj ect and assi gn i t to myGradeBook
10 GradeBook myGradeBook = newGradeBook( ) ;
11
12 / / cal l myGradeBook' s di spl ayMessage method
13 myGradeBook. di spl ayMessage( );
14 } / / end mai n
15
16 } / / end cl ass GradeBookTest

Wel come to the Grade Book!


Use class instance creation
expression to create object of
class Gr adeBook
Call method
di spl ayMessage using
Gr adeBook object
Deklarasi Method dengan Parameter
Parameter Method
Informasi tambahanyang dilewatkan melalui method
Ditambahakanpada saat memanggil method dengan
cara mengisi arguments
1 / / Fi g. 3. 4: GradeBook. j ava
2 / / Cl ass decl arati on wi th a method that has a parameter.
3
4 publ i c cl ass GradeBook
5 {
6 / / di spl ay a wel come message to the GradeBook user
7 publ i c voi d di spl ayMessage( Stri ng courseName )
8 {
9 System. out. pri ntf ( "Wel come to the grade book f or\ n%s! \ n",
10 courseName );
11 } / / end method di spl ayMessage
12
13 } / / end cl ass GradeBook

Call pr i nt f method with
cour seName argument
1 / / Fi g. 3. 5: GradeBookTest. j ava
2 / / Create GradeBook obj ect and pass a Stri ng to
3 / / i ts di spl ayMessage method.
4 i mport j ava. uti l . Scanner; / / programuses Scanner
5
6 publ i c cl ass GradeBookTest
7 {
8 / / mai n method begi ns programexecuti on
9 publ i c stati c voi d mai n( Stri ng args[] )
10 {
11 / / create Scanner to obtai n i nput f romcommand wi ndow
12 Scanner i nput = new Scanner( System. i n );
13
14 / / create a GradeBook obj ect and assi gn i t to myGradeBook
15 GradeBook myGradeBook = newGradeBook( ) ;
16
17 / / prompt f or and i nput course name
18 System. out. pri ntl n( "Pl ease enter the course name: " );
19 Stri ng nameOf Course = i nput. nextLi ne() ; / / read a l i ne of text
20 System. out. pri ntl n( ); / / outputs a bl ank l i ne
21
22 / / cal l myGradeBook' s di spl ayMessage method
23 / / and pass nameOf Course as an argument
24 myGradeBook. di spl ayMessage( nameOf Course ) ;
25 } / / end mai n
26
27 } / / end cl ass GradeBookTest

Pl ease enter the course name:
CS101 I ntroducti on to J ava Programmi ng

Wel come to the grade book f or
CS101 I ntroducti on to J ava Programmi ng!


Call next Li ne method to
read a line of input
Call di spl ayMessage with
an argument
Parameter yang lebih dari satu
Parameter ditunjukkanoleh parameter list dalam
method
Merupakan bagian dari header nya method
Menggunakan comma-separated
A compilation error occurs if the number of
arguments in a method call does not match the
number of parameters in the method declaration.
A compilation error occurs if the types of the
arguments in a method call are not consistent with
the types of the corresponding parameters in the
method declaration.
Instance Variables
Variables yang dideklarasikanpada body
method :
Disebut sebagai local variables
Hanya dapat digunakan didalammethod tersebut
Variables dideklarasikanpada class :
Disebut fields atauinstance variables
Setiapobject dari class memiliki variabel instance
yang berbeda
set Methods and get Methods
Class menyediakan public methods untuk
memperbolehkanclients dari class untuk memberikan
nilai (set) atau mengambil nilai (get) dari private
instance variables.
Nama method tidak harus dimulai dengan set atau get,
tetapi sangat direkomendasikanuntuk kepentingan
pemrogramandi J ava integrated development
environments (IDEs).
Method yang meng-assign nilai ke instance variable
disebut set method, dan method yang mengambil nilai
dari instance variable disebut get method.
set and get methods
pr i vat e instance variables
Tidakdapat diakses secara langsung oleh clients dari
object
Gunakanset methods untuk mengubahnilai variabel
Gunakanget methods untuk mengambil value variabel
Catatan : Set and Get Methods
Set methods
Disebut juga sebagai mutator methods
Memberikan nilai pada instance variables
Seharusnya divalidasi terhadapnilai baru
Dapat mengembalikan suatu nilai yang mengindikasikan data
yang salah
Get methods
Disebut juga sebagai accessor methods atau query
methods
Memperoleh / mendapatkannilai dari instance variables
Dapat dikontrol format datanya
Catatan : Set and Get Methods
Predicate methods
Penggunaan lain dari accessor methods adalah untuk
menguji apakah suatukondisi pada object : true atau
false dan mengembalikan hasilnya
Contoh: method i sEmpt y seperti linked list,
stack or queue
Access Modifiers publ i c dan pr i vat e
keyword Private
Seringdigunakan untuk instance variables
pr i vat e variables dan methods hanya bisa diakses
olehmethods di dalamclass dimana method tersebut
dideklarasikan
Deklarasi instance variables pr i vat e disebut
sebagai data hiding
Return type (Tipe Pengembalian)
Mengindikasikan item yang dikembalikan oleh method
Dideklarasikan pada header dari method
Precede every field and method declaration with an access modifier. As a rule of
thumb, instance variables should be declared pri vateand methods should be
declared publ i c. (We will see that it is appropriate to declare certain methods
pri vate, if they will be accessed only by other methods of the class.)
1 / / Fi g. 3. 7: GradeBook. j ava
2 / / GradeBook cl ass that contai ns a courseName i nstance vari abl e
3 / / and methods to set and get i ts val ue.
4
5 publ i c cl ass GradeBook
6 {
7 pri vate Stri ng courseName; / / course name f or thi s GradeBook
8
9 / / method to set the course name
10 publ i c voi d setCourseName( Stri ng name )
11 {
12 courseName = name; / / store the course name
13 } / / end method setCourseName
14
15 / / method to retri eve the course name
16 publ i c Stri ng getCourseName( )
17 {
18 return courseName;
19 } / / end method getCourseName
20
21 / / di spl ay a wel come message to the GradeBook user
22 publ i c voi d di spl ayMessage()
23 {
24 / / thi s statement cal l s getCourseName to get the
25 / / name of the course thi s GradeBook represents
26 System. out. pri ntf ( "Wel come to the grade book f or\ n%s! \ n",
27 getCourseName( ) );
28 } / / end method di spl ayMessage
29
30 } / / end cl ass GradeBook

Instance variable
cour seName
set method for cour seName
get method for cour seName
Call get method
1 / / Fi g. 3. 8: GradeBookTest. j ava
2 / / Create and mani pul ate a GradeBook obj ect.
3 i mport j ava. uti l . Scanner; / / programuses Scanner
4
5 publ i c cl ass GradeBookTest
6 {
7 / / mai n method begi ns programexecuti on
8 publ i c stati c voi d mai n( Stri ng args[] )
9 {
10 / / create Scanner to obtai n i nput f romcommand wi ndow
11 Scanner i nput = new Scanner( System. i n );
12
13 / / create a GradeBook obj ect and assi gn i t to myGradeBook
14 GradeBook myGradeBook = newGradeBook( );
15
16 / / di spl ay i ni ti al val ue of courseName
17 System. out. pri ntf ( "I ni ti al course name i s: %s\ n\ n",
18 myGradeBook. getCourseName() );
19

Call get method for
cour seName
20 / / prompt f or and read course name
21 System. out. pri ntl n( "Pl ease enter the course name: " );
22 Stri ng theName = i nput. nextLi ne(); / / read a l i ne of text
23 myGradeBook. setCourseName( theName ); / / set the course name
24 System. out. pri ntl n( ); / / outputs a bl ank l i ne
25
26 / / di spl ay wel come message af ter speci f yi ng course name
27 myGradeBook. di spl ayMessage( );
28 } / / end mai n
29
30 } / / end cl ass GradeBookTest

I ni ti al course name i s: nul l

Pl ease enter the course name:
CS101 I ntroducti on to J ava Programmi ng

Wel come to the grade book f or
CS101 I ntroducti on to J ava Programmi ng!

Call set method for
cour seName
Call di spl ayMessage
Tugas 1
Buat class dan penggunaan class dari
permasalahan Lingkaran dengan ketentuan:
Nama Class : Circle.java
Pengguna Class : CircleTest.java
Atribut Class Circle :
radius
Method Class Circle :
setRadius
getArea
getPerimeter
afif.supianto@ub.ac.i d
081 331 834 734 / 088 160 127 40

Anda mungkin juga menyukai