PEMROGRAMAN LANJUT Sistem Informasi FILKOM UB Semester Genap 2016/2017 Lebih Jauh Tentang CLASS & OBJEK pada Object Oriented Programming Dr. Eng. Herman Tolle, ST., MT Fakultas Ilmu Komputer, Universitas Brawijaya
Pemrograman Lanjut 1. Nama Matakuliah : PemrogramanLanjut 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) Rabu, 14.30 16.10, Ruang B1.8 (Praktikum)
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 More about UML Class Diagram
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 Mahasiswamampumembuat 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 5. Array of Object
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 3. Object dapat dalam bentuk array (array of object)
Kamu Harus Tahu Objek (dalam bentuk kelas) banyak yang sudah disediakan oleh program Java, dikenal dengan Predefined 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 Defined Class
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. Pelajari materi tentang UML Class Relation Notation!
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. 9
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 {...... Aggregated class Aggregating class Aggregated class 10
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. RelasiAggregasiataupunkomposisi karena direpresentasi menggunakan class dengan cara yang mirip/sama, maka kadang disebut dengan komposisi saja 11
import java.util.date; public final class Person { private String firstname; private String lastname; private Date dob; Contoh 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; Person Sales1 = new ( John, Doe, 03/27/1990 );
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 Outline 13 Date.java (1 of 3)
Outline 14 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)
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 Outline 15 Date.java (3 of 3)
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 Outline 16 Employee.java Implicit calls to hiredate and birthdate s tostring methods
1 // Fig. 8.9: EmployeeTest.java 2 // Composition demonstration. 3 4 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 Outline 17 EmployeeTest. Create an Employee java object Display the Employee object
class Point { int X; int Y; int Z; Point.java 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;
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' 19
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. 20
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); 21
Example Java assigns no default value to a local variable inside a method. 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 22
Wrapper Classes q Boolean q Character q Short q Byte q Integer q Long q Float q Double 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. 23 23
The Integer and Double Classes -value: int +MAX_VALUE: int +MIN_VALUE: int java.lang.integer -value: double +MAX_VALUE: double +MIN_VALUE: double java.lang.double +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 +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 +parsedouble(s: String, radix: int): double 24 24
Contoh Kasus: 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); Output? alas bertipe data int (primitif) Tinggi bertipe data Integer (object reference wrapper)
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 dalammethod Penggunaan object sbg argument berbeda dalam eksekusi jikadibandingkandenganvariabel biasasbg argumen public static void modify(student s) { s.marks = 100;
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 28
Passing Objects to Methods, cont. 29
Contoh public class Student { int marks; 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;
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. Deklarasiobjek sebagai array 2. Membuat (Create) objek dengan menggunakan konstruktor
Contoh class Student { int marks; // 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;
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 masingmasing 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 Deadline: 10 April 2016, Dikirim ke email dosen.
MATERI TAMBAHAN
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 atau kombinasi dari ke-3 hal tersebut
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 Jika 3 argumen input berarti untuk masing-masing Panjang, Lebar dan Tinggi
public class Kubus { private int panjang, lebar, tinggi; Class Kubus 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
public class KubusBeraksi { public static void main(args[]) { Kubus Balok1 = new Balok(5, 5, 5); Kubus Balok2 = new Balok(); Class Kubus 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()); Cari tahu apa keluaran dari program ini!
Example public class Student { private int id; private BirthDate birthdate; public class BirthDate { private int year; private int month; private int day; 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 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! 49
Deitel, Java How to Program Acknowledgements
Terima Kasih