PEMROGRAMAN LANJUT
Fakultas Ilmu Komputer, Universitas Brawijaya
Lebih Jauh Tentang
CLASS & OBJEK
pada
Object Oriented Programming
Dr. Eng. Herman Tolle, ST., MT
Sistem Informasi FILKOM UB Semester Genap 2016/2017
Pemrograman Lanjut
1. Nama Matakuliah
:
Pemrograman Lanjut
2. Kode/SKS
: CSD60022
/ 5 (4-1) SKS
3. Semester
: Genap
4. Kelas
: A
5. Program Studi
: Teknologi Informasi –Universitas Brawijaya
6. Dosen
: Dr. Eng. Herman Tolle, ST., MT.
7. Asisten
:
8. Jadwal Kuliah
:
– Senin, 14.30 – 16.10, Ruang E1.2 (Teori)
– Selasa, 07.00 – 8.40, Ruang A2.20 (Teori)
Info Pertemuan
Tanggal
: 27 Maret 2017
Ruang & Waktu
: E1.2, Jam 14.30 – 16.00
Materi
: Lebih Jauh Tentag Class & Objek
• Class Composistion | Relasi Antar Kelas
• Array of Object
Tujuan Pembelajaran
Setelah mengikuti materi ini, diharapkan
• Mahasiswa dapat memahami konsep relasi antar Objek
dalam pemrograman berorientasi obyek (OOP)
• Mengenal berbagai notasi terkait relasi antar kelas
• Memahami konsep objek sebagai parameter passing
• Memahami konsep array of object
• Mahasiswa mampu membuat program yang menerapkan
penggunaan komposisi class, objek sebagai passing
parameter dan objek array
Kata Kunci / Keyword
1. Class Relation
2. Class Composition
3. Aggregation
4. Passing Parameter | objek sebagai argumen
method
Fleksibilitas Object
• Objek dapat berperilaku layaknya sebuah variabel
(dengan tipe data)
1. Objek dapat digunakan sebagai anggota kelas
(komposisi) dari kelas yang lain
2. Objek dapat sebagai argument dalam method
Kamu Harus Tahu
• Objek (dalam bentuk kelas) banyak yang sudah
disediakan oleh program Java, dikenal dengan
Pre-defined Class
– Misalnya: Kelas Math, String, Date, dll
• Objek (dalam bentuk kelas) juga bisa dibuat oleh
programmer yang kemudian dapat digunakan pada
program-program yang berbeda, dikenal sbg
User
Komposisi
• Komposisi
– Sebuah kelas dapat memiliki member yang
merupakan referensi objek dari kelas yang lain.
– Terkoneksi dalam hubungan has-a
• Salah satu bentuk dari software reuse adalah
composition, dimana sebuah kelas memiliki
member yang berupa objek dari kelas yang
lain.
9
Object Composition
Composition is actually a special case of the aggregation
relationship.
Aggregation models has-a relationships and represents an
ownership relationship between two objects. The owner object
is called an aggregating object and its class an aggregating class.
The subject object is called an aggregated object and its class an
aggregated class.
10
Class Representation
An aggregation relationship is usually represented as a
data field in the aggregating class. For example, the
relationship in Figure 10.6 can be represented as follows:
public class Name { ...
}
public class Student { private Name name;
private Address address; ...
}
public class Address { ...
}
11
Aggregation or Composition
• Since aggregation and composition
relationships are represented using classes in
similar ways, many texts don’t differentiate
them and call both compositions.
• Relasi Aggregasi ataupun komposisi karena
direpresentasi menggunakan class dengan cara
yang mirip/sama, maka kadang disebut dengan
Contoh
import java.util.Date;
public final class Person {
private String firstName; private String lastName;
private Date dob;
public Person(String firstName, String lastName, Date dob) {
this.firstName = firstName; this.lastName = lastName; this.dob = dob;
}
public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } public Date getDOB()
{ return this.dob; }
13
Outline
1 // Fig. 8.7: Date.java 2 // Date class declaration. 3
4 public class Date
5 {
6 private int month; // 1-12
7 private int day; // 1-31 based on month 8 private int year; // any year
9
10 // constructor: call checkMonth to confirm proper value for month; 11 // call checkDay to confirm proper value for day
12 public Date( int theMonth, int theDay, int theYear )
13 {
14 month = checkMonth( theMonth ); // validate month 15 year = theYear; // could validate year
16 day = checkDay( theDay ); // validate day 17
18 System.out.printf(
19 "Date object constructor for date %s\n", this );
20 } // end Date constructor 21
• Date.java • (1 of 3)
14
Outline
22 // utility method to confirm proper month value
23 private int checkMonth( int testMonth )
24 {
25 if ( testMonth > 0 && testMonth <= 12 ) // validate month
26 return testMonth;
27 else // month is invalid
28 {
29 System.out.printf(
30 "Invalid month (%d) set to 1.", testMonth );
31 return 1; // maintain object in consistent state
32 } // end else
33 } // end method checkMonth
34
35 // utility method to confirm proper day value based on month and year
36 private int checkDay( int testDay )
37 { 38 int daysPerMonth[] = 39 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 40 Validates month value Validates day value • Date.java • (2 of 3)
15
Outline
• Date.java • (3 of 3)
41 // check if day in range for month
42 if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
43 return testDay;
44
45 // check for leap year
46 if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
47 ( year % 4 == 0 && year % 100 != 0 ) ) )
48 return testDay;
49
50 System.out.printf( "Invalid day (%d) set to 1.", testDay );
51 return 1; // maintain object in consistent state 52 } // end method checkDay
53
54 // return a String of the form month/day/year 55 public String toString()
56 {
57 return String.format( "%d/%d/%d", month, day, year );
58 } // end method toString 59 } // end class Date
Check if the day is February 29 on a leap year
16
Outline
• Employee.java
1 // Fig. 8.8: Employee.java
2 // Employee class with references to other objects. 3
4 public class Employee
5 {
6 private String firstName;
7 private String lastName;
8 private Date birthDate;
9 private Date hireDate;
10
11 // constructor to initialize name, birth date and hire date 12 public Employee( String first, String last, Date dateOfBirth,
13 Date dateOfHire ) 14 { 15 firstName = first; 16 lastName = last; 17 birthDate = dateOfBirth; 18 hireDate = dateOfHire;
19 } // end Employee constructor
20
21 // convert Employee to String format 22 public String toString()
23 {
24 return String.format( "%s, %s Hired: %s Birthday: %s",
25 lastName, firstName, hireDate, birthDate );
26 } // end method toString
27 } // end class Employee
Employee contains
references to two Date objects
Implicit calls to hireDate and
birthDate’s toString
17
Outline
• EmployeeTest. java 1 // Fig. 8.9: EmployeeTest.java 2 // Composition demonstration. 34 public class EmployeeTest
5 {
6 public static void main( String args[] )
7 {
8 Date birth = new Date( 7, 24, 1949 );
9 Date hire = new Date( 3, 12, 1988 );
10 Employee employee = new Employee( "Bob", "Blue", birth, hire );
11
12 System.out.println( employee );
13 } // end main
14 } // end class EmployeeTest
Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988
Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949
Create an Employee object
Display the Employee object
Point.java
class Point { int X; int Y; int Z; } class Line { Point T1; Point T2;public Line(Point A, Point B) { T1 = A;
T2 = B; }
public double GetLength() { int X = T2.X – T1.X; int Y int Z double L = Math.sqrt((X*X)+(Y*Y)+(Z*Z)); return L; }
19
Reference Data Fields
The data fields can be of reference types. For example,
the following Student class contains a data field name
of the String type.
public class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; // c has default value '\u0000'
20
The null Value
Jika sebuah atribut (data field) yang bertipe
reference tidak me-refer ke objek manapun
(tidak/belum diisi nilainya), maka atribut tsb
memiliki nilai literal khusus yaitu:
null
.
21
Default Value for a Data Field
The default value of a data field is null for a reference
type, 0 for a numeric type, false for a boolean type, and
'\u0000' for a char type. However, Java assigns no
default value to a local variable inside a method.
public class Test {
public static void main(String[] args) { Student student = new Student();
System.out.println("name? " + student.name); System.out.println("age? " + student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("gender? " + student.gender); } }
22
Example
public class Test {
public static void main(String[] args) { int x; // x has no default value
String y; // y has no default value System.out.println("x is " + x); System.out.println("y is " + y); }
}
Compile error: variable not initialized
Java assigns no default value to a local variable
inside a method.
23 23
Wrapper Classes
q Boolean
q Character
q Short
q Byte
qInteger
qLong
qFloat
qDouble
NOTE: (1) The wrapper classes do
not have no-arg constructors. (2)
The instances of all wrapper
classes are immutable, i.e., their
internal values cannot be changed
once the objects are created.
24
24
The
Integer
and
Double
Classes
java.lang.Integer -value: int +MAX_VALUE: int +MIN_VALUE: int +Integer(value: int) +Integer(s: String) +byteValue(): byte +shortValue(): short +intValue(): int +longVlaue(): long +floatValue(): float +doubleValue():double
+compareTo(o: Integer): int +toString(): String
+valueOf(s: String): Integer
+valueOf(s: String, radix: int): Integer +parseInt(s: String): int
+parseInt(s: String, radix: int): int
java.lang.Double -value: double +MAX_VALUE: double +MIN_VALUE: double +Double(value: double) +Double(s: String) +byteValue(): byte +shortValue(): short +intValue(): int +longVlaue(): long +floatValue(): float +doubleValue():double
+compareTo(o: Double): int +toString(): String
+valueOf(s: String): Double
+valueOf(s: String, radix: int): Double +parseDouble(s: String): double
public class Segitiga {
int alas;
Integer tinggi;
}
public static void main(String[] args) {
Segitiga SG3 = new Segitiga();
S.o.p("alas= " + SG3.alas + ", tinggi= "+ SG3.tinggi); }
Contoh Kasus:
Output?
alas bertipe data int (primitif)
OBJ ECT SEBAGAI ARGUMEN METHOD
(PASSING PARAMETER)
Object sebagai Argumen Method
• Objek dapat berperilaku layaknya sebuah variabel (dengan
tipe data)
• Objek dapat digunakan sebagai anggota kelas
• Objek dapat sebagai argument dalam method
• Penggunaan object sbg argument berbeda dalam eksekusi
jika dibandingkan dengan variabel biasa sbg argumen
public static void modify(Student s) { s.marks = 100;
28
Passing Objects to Methods
q Passing by value for primitive type value (the value is
passed to the parameter)
q Jika parameter adalah tipe data primitive, maka yg
dikirimkan adalah nilai atau value nya.
q Passing by value for reference type value (the value is
the reference to the object)
q Jika parameter adalah objek (reference), maka yang
dikirimkan adalah lokasi objeknya, sehingga perubahan
nilai objek dapat saja terjadi
29
Contoh
public static void main(String[] args) {
Student Siswa1 = new Student(); Siswa1.marks = 99;
System.out.println(Siswa1.marks); // prints 99
modify(Siswa1);
System.out.println(Siswa1.marks); // prints 100 and not 99
}
public static void modify(Student s) { s.marks = 100;
}
public class Student { int marks;
ARRAY of OBJECT
• Object dalam prakteknya dapat digunakan layaknya variabel
dengan tipe data tertentu.
• Deklarasi array dari objek dapat dilakukan layaknya deklarasi
variable dengan tipe data tertentu
• Penggunaan objek array mirip dengan penggunaan variable
array
Ada 2 tahapan deklarasi objek array:
1. Deklarasi objek sebagai array
Contoh
// Tahap 1: Deklarasi Objek sebagai Array
Student[] studentArray = new Student[7];
// Tahap 2: Create objek array dengan Konstruktor
studentArray[0] = new Student();
// contoh akses object member
studentArray[0].marks = 99;
class Student {
int marks;
}
Contoh
Film films[] = new Film[4];
films[0] = new Film("Shrek",133);
films[1] = new Film("Road to Perdition",117);
films[2] = new Film("The Truth about Cats and Dogs",93);
films[3] = new Film("Enigma",114);
Deklarasi Objek String dalam Class
public class Mahasiswa{
private String Nama; private String NIM;
private String[] KodeMK = new String[10]; private String[] NamaMK = new String[10]; }
public static Mahasiswa(String N, String NIM) { this.Nama = N;
this.NIM = NIM; }
Satu mahasiswa bisa mempunyai banyak banyak MK, atau mengambil/memprogram banyak MK
Deklarasi Objek Reference dalam Class
public class MataKuliah{
private String KodeMK; private String NamaMK; private int SKS;
}
public class Mahasiswa {
private String Nama; private String NIM;
private MataKuliah[] KRS = new MataKuliah[10];
Deklarasi Array Objek dalam Loop
public static void main(String args[]) {
Mahasiswa MhsTI[] = new Mahasiswa[5]; // 1
for (int i=0; i<3; i++) // Input Data {
Sout(“Nama “); String Nama = input.nextLine(); Sout(“NIM “); String NIM = input.nextLine();
MhsTI[i] = new Mahasiswa(Nama, NIM); // 2
} }
Latihan Studi Kasus
• Sistem Informasi Akademik Mahasiswa sederhana
• Buat Kelas Mahasiswa à Nama, NIM, Prodi, MK (array)
• Kelas MK: KodeMK, Nama MK, SKS, Nilai
• Buat program yang menggunakan kelas Mahasiswa tsb à
Objek Mahasiswa TI dalam array (mis: 3 mhs), Input
masing-masing 5 MK beserta Nilai
Studi Kasus
public class Mahasiswa {
private String Nama; private String NIM;
private MK[] KHS = new MK[10]; }
public class MK {
private String KodeMK; private String NamaMK; private int SKS;
private String Nilai; }
public static void main(String args[]) {
Mahasiswa MhsTI[] = new Mahasiswa[5]; for (int i=0; i<3; i++) // Input Data {
Sout(“Nama :“); String Nama = input.nextLine(); Sout(“NIM :“); String NIM = input.nextLine(); Sout(“Prodi :“); String Prodi = input.nextLine(); MhsTI[i] = new Mahasiswa(Nama, NIM, Prodi);
}
for (int i=0; i<3; i++) // Input Data KRS/KHS {
Sout(“MK ke-“, i); String KodeMK = input.nextLine();
Sout(“NamaMK ke-“, i); String NamaMK = input.nextLine(); Sout(“SKS “); int SKS = input.nextInt();
Sout(“Nilai “); String Nilai = input.nexLine(); MK MKInput = new MK(KodeMK, NamaMK, SKS, Nilai)
MhsTI[1].setMK(MKInput);
} }
Studi Kasus: Sistem Penggajian Pegawai
Employee -fullName: string; - birthDate: date; -hireDate: date; -salary: Salary;-numberOfEmployee: int static +employee(name, birth) +getName(): string +getBirthdate(); date -day: int; - month: int; - year int; + date(d,m,y); + setDate(d, m, y); Salary - gajiPokok + hitungGaji()
Tugas 5
Studi Kasus: Pegawai & Gaji Harian
• Pengembangan dari tugas sebelumnya, dengan
menambahkan atribut baru (birthday , hiredate, salary)
• Rule baru:
1.
Jika masa kerja > 3 bulan maka Gaji Pokok lebih besar z% atau x
rupiah (ditentukan sendiri berapa besarannya)
2.
Jika umur > y tahun maka dapat Tunjangan Lain-lain sebesar w
rupiah
Laporan
• Soal (Kasus, Rules, Konstanta)
• Diagram Class beserta relasinya
• Buat implementasi class
• Buat program implementasi class, min 3
pegawai dan dengan menggunakan Array of
objrct
• Screenshot
Modular Programming
• Memisahkan data dengan proses
Contoh:
• menggunakan konstanta
– final static int gajiPokok = 5000;
– final static int minKerja = 3;
– final static double gajiNaik = 0.2;
• Rules:
– If (lamaKerja > minKerja) gajiPokokPegawai = gajiPokok
* (1 + gajiNaik);
Overloading METHOD
• Method sebagai Class Member yang
memiliki nama yang sama tetapi dapat
berbeda dalam hal:
– Jumlah parameter / argumen input,
– Tipe data parameter / argumen input
– Tipe data keluaran
Contoh: Kelas Kubus
• Buatlah sebuah kelas Kubus dengan 3 atribut yaitu: Panjang,
Lebar dan Tinggi.
• Konstruktor digunakan untuk menginput 3 atribut, atau jika
konstruktor tidak dengan input maka 3 atribut ditentukan
bernilai 10
• Buat satu fungsi dengan nama yang sama untuk meng-SET
atribut kubus.
– Jika 1 argumen input: 3 atribut kubus memiliki nilai yang sama,
– Jika 2 argumen input berarti untuk Panjang dan Lebar sedangkan tinggi di-set = 10
Class Kubus
public class Kubus
{
private int panjang, lebar, tinggi; public Kubus()
{ this(10, 10, 10); }
public Kubus(int P, int L, int T) { this.panjang = P;
this.lebar = L; this.tinggi = T; }
public void setAtribut(int P) { this.panjang = P;
this.lebar = P; this.tinggi = P; }
public void setAtribut(int P, int L) { this.panjang = P; this.lebar = L; this.tinggi = 10; } } Overloading konstruktor
Class Kubus
public class KubusBeraksi
{
public static void main(args[]) {
Kubus Balok1 = new Balok(5, 5, 5); Kubus Balok2 = new Balok();
Balok1 = Balok2;
S.o.p(“ Balok1 Panjang = “ + Balok1.getPanjang()); S.o.p(“ Balok1 Tinggi = “ + Balok1.getTinggi());
Balok2.setAtribut(7,8);
S.o.p(“ Balok1 Panjang = “ + Balok1.getPanjang()); S.o.p(“ Balok1 Tinggi = “ + Balok1.getTinggi()); }
}
49
Example
public class Student {private int id;
private BirthDate birthDate; public Student(int ssn,
int year, int month, int day) { id = ssn;
birthDate = new BirthDate(year, month, day); }
public int getId() { return id;
}
public BirthDate getBirthDate() { return birthDate;
} }
public class BirthDate { private int year;
private int month; private int day;
public BirthDate(int newYear, int newMonth, int newDay) { year = newYear;
month = newMonth; day = newDay;
}
public void setYear(int newYear) { year = newYear;
} }
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is changed! }