Senin, 27 Februari 2017

Class dan Object studi kasus Ticket Machine

     Berikut adalah penggunaan object dan class pada studi kasus Ticket Machine. Ticket Machine sendiri adalah program untuk mengatur harga tiket, mengatur kembalian uang dan mencetak tiket sebagai bukti pembelian.
  • Source code untuk class TimeMachine
 /**  
  * Nama file: TicketMachine.java  
  *   
  * Fakhriyah 5115100126  
  */  
 public class TicketMachine  
 {  
   // The price of a ticket from this machine.  
   private int price;  
   // The amount of money entered by costumer so far.  
   private int balance;  
   // The total amount of money collected by this machine.  
   private int total;  
   /**  
    * Create a machine that issues tickets of the given price.  
    * Note that the price must be greater than zero, and there  
    * are no checks to ensure this.  
    */  
   public TicketMachine( int ticketCost )  
   {  
     price = ticketCost;  
     balance = 0;  
     total = 0;  
   }  
   /**  
    * Return the price of a ticket.  
    */  
   public int getPrice()  
   {  
     return price;  
   }  
   /**  
    * Return the amount of money already inserted for the  
    * next ticket.  
    */  
   public int getBalance()  
   {  
     return balance;  
   }  
   /**  
    * Return an amount of money in cents from a costumer.  
    */  
   public void insertMoney( int amount )  
   {  
     balance = balance + amount;  
   }  
   /**  
    * Print a ticket.  
    * Update the total collected and  
    * reduce the balance to zero.  
    */  
   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;  
   }  
 }  
  • Source code untuk class IntMain
 /**  
  * Nama file: IntMain.java  
  *   
  * Fakhriyah 5115100126  
  */  
 import java.util.Scanner;  
 public class IntMain  
 {  
   public static void main(String args[])  
   {  
     Scanner scan = new Scanner(System.in);  
     int cost, menu;  
     System.out.println("Masukkan harga tiket \n");  
     cost = scan.nextInt();  
     TicketMachine ticket = new TicketMachine(cost);  
     while (true)  
     {  
       System.out.println("1. Get Price");  
       System.out.println("2. Get Balance");  
       System.out.println("3. Insert Money");  
       System.out.println("4. Print Ticket");  
       menu = scan.nextInt();  
       switch(menu)  
       {  
         case 1:  
         cost = ticket.getPrice();  
         System.out.println(cost);  
         break;  
         case 2:  
         System.out.println(ticket.getBalance());  
         break;  
         case 3:  
         int money = scan.nextInt();  
         ticket.insertMoney(money);  
         break;  
         case 4:  
         ticket.printTicket();  
         break;  
       }  
     }  
   }  
 }  

     Setelah kedua program tersebut dicompile, maka kita tinggal menjalankan program tersebut, dan seperti berikut inilah hasil outputnya:

  • Pada tampilan awal kita diminta untuk memasukkan harga tiket, kita bisa memasukkan harga tiket sesuai dengan keinginan kita sebagai percobaan.
  • Setelah kita memasukkan harga tiket, maka akan muncul 4 pilihan menu, yaitu menampilkan harga tiket, menampilkan uang yang telah dimasukkan ke dalam mesin, memasukkan uang ke dalam mesin dan mencetak tiket.
  • Untuk mengecek program, maka kita akan memilih pilihan 1, yaitu untuk menampilkan harga tiket.
  • Selanjutnya pilihan 2, untuk menampilkan uang yang telah dimasukkan ke dalam mesin. Karena kita belum memasukkan uang ke dalam mesin, maka hasil yang muncul adalah 0.
  • Oleh karena itu, kita memilih pilihan 3, yaitu untuk memasukkan uang ke dalam mesin, kita bebas memasukkan uang berapa saja. Setelah itu, kita cek kembali uang yang telah masuk menggunakan pilihan 2.

  • Yang terakhir, kita akan memilih pilihan 4 untuk mencetak tiket.

Classes and Objects

8.1 Introduction

8.2 Time Class Study

 /**  
  * Fig. 8.1: Time1.java  
  * Time1 class declaration maintains the time in 24-hour format.
  * Fakhriyah 5115100126
  */  
 public class Time1  
 {  
   private int hour;  // 0 - 23  
   private int minute; // 0 - 59  
   private int second; // 0 - 59  
   //set a new time value using universal time; throw an  
   // exception if the hour, minute or second is invalid  
   public void setTime( int h, int m, int s )  
   {  
     //validate hour, minute and second  
     if ( ( h >= 0 && h < 24 ) && ( m >= 0 &&m < 60) &&  
       ( s >= 0 && s < 60 ) )  
       {  
         hour = h;  
         minute = m;  
         second = s;  
       } // end if  
       else  
         throw new IllegalArgumentException(  
           "hour, minute and/or second was out of range" );  
   } //end method setTime  
   // convert to String in universal-time format (HH:MM:SS)  
   public String toUniversalString()  
   {  
     return String.format( "%02d:%02d:%02d", hour, minute, second );  
   } // end method toUniversalString  
   //convert to String in standard-time format (H:MM:SS AM or PM)  
   public String toString()  
   {  
     return String.format( "%d:%02d:%02d %s",  
       ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),  
       minute, second, ( hour < 12 ? "AM" : "PM" ) );  
   } //end method toString  
 } // end class Time1  


 /**  
  * Fig. 8.2: Time1Test.java  
  * Time1 objct used in an application.
  * Fakhriyah 5115100126  
  */  
 public class Time1Test  
 {  
   public static void main ( String[] args )  
   {  
     // creat and initializa a Time1 object  
     Time1 time = new Time1();  // invokes Time1 constructor  
     // output string representations of the time  
     System.out.print( "The initial universal time is: " );  
     System.out.println( time.toUniversalString() );  
     System.out.print( "The initial standard time is: " );  
     System.out.println( time.toString() );  
     System.out.println();  // output a blank line  
     // change time and output updated time  
     time.setTime( 13, 27, 6 );  
     System.out.print( "Universal time after setTime is: " );  
     System.out.println( time.toUniversalString() );  
     System.out.print( "Standard time after setTime: " );  
     System.out.println( time.toString() );  
     System.out.println();  // output a blank line  
     // attempt to set time with invalid values  
     try  
     {  
       time.setTime( 99, 99, 99 ); // all values out of range  
     }  // end try  
     catch ( IllegalArgumentException e )  
     {  
       System.out.printf( "Exception: %s\n\n", e.getMessage() );  
     }  // end catch  
     // display time after attempt to set invalid values  
     System.out.println( "After attempt invalid settings:" );  
     System.out.print( "Universal time: " );  
     System.out.println( time.toUniversalString() );  
     System.out.print( "Standard time: " );  
     System.out.println( time.toString() );  
   }  // end main  
 }  // end class Time1Test  

Outputnya:


8.3 Controlling Access to Members

 /**  
  * Fig. 8.3: MemberAccessTest.java  
  * Private members of class Time1 are not accessible.  
  * Fakhriyah 5115100126
  */  
 public class MemberAccessTest  
 {  
   public static void main( String[] args )  
   {  
     Time1 time = new Time1();  // create and initialize Time1 object  
     time.hour = 7;    // error: hour has private access in Time1  
     time.minute = 15;  // error: minute has private access in Time1  
     time.second = 30;  // error: second has private access in Time1  
   }  // end main  
 }  // end class MemberAccessTest  

8.4 Referring to the Current Object's Members with the this Reference

 /**  
  * Fig. 8.4: ThisTest.java  
  * this used implicity and explicity to refer to members of an object.  
  * Fakhriyah 5115100126
  */  
 public class ThisTest  
 {  
   public static void main( String[] args)  
   {  
     SimpleTime time = new SimpleTime( 15, 30, 19 );  
     System.out.println( time.buildString() );  
   }  // end main  
 }  // end class ThisTest  
 // class SimpleTime demonstrates the "this" reference  
 class SimpleTime  
 {  
   private int hour;  // 0-23  
   private int minute; // 0-59  
   private int second; // 0-59  
   // if the construction uses parameter names identical to  
   // instance variable names the "this" reference is  
   // required to distinguish between the names  
   public SimpleTime( int hour, int minute, int second )  
   {  
     this.hour = hour;    // set "this" object's hour  
     this.minute = minute;  // set "this" object's minute  
     this.second = second;  // set "this" object's second  
   }  // end SimpleTime constructor  
   // use explicit and implicit "this to call toUniversalString  
   public String buildString()  
   {  
     return String.format( "%24s: %s\n%24s: %s",  
       "this.toUniversalString()", this.toUniversalString(),  
       "toUniversalString()", toUniversalString() );  
   }  // end method buildString  
   // convert to String in universal-time format (HH:MM:SS)  
   public String toUniversalString()  
   {  
     // "this" is not required here to access instance variables,  
     // because method does not have local variables with same  
     // name as instance variables  
     return String.format( "%02d:%02d:%02d",  
       this.hour, this.minute, this.second );  
   }  // end method toUniversalString  
 }  // end class SimpleTime  

Outputnya:


8.5 Time Class Case Study: Overloaded Constructions

 /**  
  * Fig. 8.5: Time2.java  
  * TIme2 class declaration with overloaded constructors. 
  * Fakhriyah 5115100126 
  */  
 public class Time2  
 {  
   private int hour;  // 0 - 23  
   private int minute; // 0 - 59  
   private int second; // 0 -59  
   // Time2 no-argument constructor:  
   // initializes each instance variable to zero  
   public Time2()  
   {  
     this( 0, 0, 0); // invoke Time2 constructor with three arguments  
   }  // end Time2 no-argument constructor  
   // Time2 constructor: hour supplied, minute and second defaulted to 0  
   public Time2( int h )  
   {  
     this( h, 0, 0 );  // invoke Time2 constructor with three arguments  
   }  // end Time2 one-argument constructor  
   // Time2 constructor: hour and minute supplied, second defaulted to 0  
   public Time2( int h, int m )  
   {  
     this( h, m, 0 );  // invoke Time2 constructor with three arguments  
   }  // end Time2 two-argument constructor  
   // Time2 constructor: hour, minute and second supplied  
   public Time2( int h, int m, int s )  
   {  
     setTime( h, m, s ); // invoke setTime to validate time  
   }  // end Time2 three-argument constructor  
   // Time2 constructor: another Time2 object supplied  
   public Time2( Time2 time )  
   {  
     // invoke Time2 three-argument constructor  
     this( time.getHour(), time.getMinute(), time.getSecond() );  
   }  // end Time2 constructor with a Time2 object argument  
   // Set Methods  
   // set a new time value using universal time;  
   // validate the data  
   public void setTime( int h, int m, int s )  
   {  
     setHour( h );  // set the hour  
     setMinute( m ); // set the minute  
     setSecond( s ); // set the second  
   }  // end method setTime  
   // validate and set hour  
   public void setHour( int h )  
   {  
     if( h >= 0 && h < 24 )  
       hour = h;  
     else  
       throw new IllegalArgumentException( "hour must be 0-23" );  
   }  // end method setHour  
   // validate and set minute  
   public void setMinute( int m )  
   {  
     if( m >= 0 && m < 60 )  
       minute = m;  
     else  
       throw new IllegalArgumentException( "minute must be 0-59" );  
   }  // end method setMinute  
   // validate and set second  
   public void setSecond( int s )  
   {  
     if( s >= 0 && s < 60 )  
       second = s;  
     else  
       throw new IllegalArgumentException( "second must be 0-59" );  
   }  // end method setSecond  
   // Get Methods  
   // get hour value  
   public int getHour()  
   {  
     return hour;  
   }  // end method getHour  
   // get minute value  
   public int getMinute()  
   {  
     return minute;  
   }  // end method getMinute  
   // get second value  
   public int getSecond()  
   {  
     return second;  
   }  // end method getSecond  
   // convert to String in universal-time format (HH:MM:SS)  
   public String toUniversalString()  
   {  
     return String.format( "%02d:%02d:%02d", getHour(), getMinute(), getSecond() );  
   }  // end method toUniversalString  
   //convert to String in standard-time format (H:MM:SS AM or PM)  
   public String toString()  
   {  
     return String.format( "%d:%02d:%02d %s",   
       ( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12), getMinute(), getSecond(),   
       ( getHour() < 12 ? "AM" : "PM" ) );  
   }  // end method toString  
 }  // end class Time2  


 /**  
  * Fig. 8.6: Time2Test.java  
  * Overloaded constructors used to initialized Time2Objects.
  * Fakhriyah 5115100126  
  */  
 public class Time2Test  
 {  
   public static void main( String[] args )  
   {  
     Time2 t1 = new Time2();       // 00:00:00  
     Time2 t2 = new Time2( 2 );     // 02:00:00  
     Time2 t3 = new Time2( 21, 34 );   // 21:34:00  
     Time2 t4 = new Time2( 12, 25, 42 ); // 12:25:42  
     Time2 t5 = new Time2( t4 );     // 12:25:42  
     System.out.println( "Constructed with:" );  
     System.out.println( "t1: all arguments defaulted" );  
     System.out.printf( " %s\n", t1.toUniversalString() );  
     System.out.printf( " %s\n", t1.toString() );  
     System.out.println( "t2: hour specified; minute and second defaulted" );  
     System.out.printf( " %s\n", t2.toUniversalString() );  
     System.out.printf( " %s\n", t2.toString() );  
     System.out.println( "t3: hour and minute specified; second defaulted" );  
     System.out.printf( " %s\n", t3.toUniversalString() );  
     System.out.printf( " %s\n", t3.toString() );  
     System.out.println( "t4: hour, minute and second specified" );  
     System.out.printf( " %s\n", t4.toUniversalString() );  
     System.out.printf( " %s\n", t4.toString() );  
     System.out.println( "t5: Time2 object t4 specified" );  
     System.out.printf( " %s\n", t5.toUniversalString() );  
     System.out.printf( " %s\n", t5.toString() );  
     // attempt to initialize t6 with invalid values  
     try  
     {  
       Time2 t6 = new Time2( 27, 74, 99 ); // invalid values  
     }  // end try  
     catch ( IllegalArgumentException e )  
     {  
       System.out.printf( "\nException while initializing t6: %s\n", e.getMessage() );  
     }  // end catch  
   }  // end main  
 }  // end class Time2Test  


8.6 Default and No-Argument Constructor

8.7 Notes on Sets and Gets Methods

8.8 Composition

 /**  
  * Fig. 8.7: Date.java  
  * Date class declaration.  
  * Fakhriyah 5115100126
  */  
 public class Date  
 {  
   private int month; // 1-12  
   private int day;  // 1-31 based on month  
   private int year;  // any year  
   private static final int[] daysPerMonth =  // days in each month  
     { 0, 31, 28, 31, 30, 31, 30, 31, 30, 31, 30, 31 };  
   // constructor: call checkMonth to confirm proper value for month;  
   // call checkDay to confirm proper value for day  
   public Date( int theMonth, int theDay, int theYear )  
   {  
     month = checkMonth( theMonth ); // validate month  
     year = theYear;         // could validate year  
     day = checkDay( theDay );    // validate day  
     System.out.printf( "Date object constructor for date %s\n", this );  
   }  // end Date constructor  
   // utility method to confirm proper month value  
   private int checkMonth( int testMonth )  
   {  
     if ( testMonth > 0 && testMonth <= 12 ) // validate month  
       return testMonth;  
     else  // month is invalid  
       throw new IllegalArgumentException( "month must be 1-12" );  
   }  // end method checkMonth  
   // utility method to confirm proper day value based on month and year  
   private int checkDay( int testDay )  
   {  
     // check if day in range for month  
     if ( testDay > 0 && testDay <= daysPerMonth[ month ] )  
       return testDay;  
     // check for leap year  
     if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||  
       ( year % 4 == 0 && year % 100!= 0 ) ) )  
       return testDay;  
     throw new IllegalArgumentException( "day out-of-range for the specified month and year" );  
   }  // end method checkDay  
   // return a String of the form month/day/year  
   public String toString()  
   {  
     return String.format( "%d/%d/%d", month, day, year );  
   }  // end method toString  
 }  // end class Date  


 /**  
  * Fig. 8.8: Employee.java  
  * Employee class with references to other objects. 
  * Fakhriyah 5115100126 
  */  
 public class Employee  
 {  
   private String firstName;  
   private String lastName;  
   private Date birthDate;  
   private Date hireDate;  
   // constructor to initialize name, birth day and hire date  
   public Employee( String first, String last, Date dateOfBirth, Date dateOfHire )  
   {  
     firstName = first;  
     lastName = last;  
     birthDate = dateOfBirth;  
     hireDate = dateOfHire;  
   }  // end Employee constructor  
   // convert Employee to String format  
   public String toString()  
   {  
     return String.format( "%s, %s Hired: %s Birthday: %s",   
       lastName, firstName, hireDate, birthDate );  
   }  // end method toString  
 }  // end class Employee  


 /**  
  * Fig. 8.9: EmployeeTest.java  
  * Composition demonstration.  
  * Fakhriyah 5115100126
  */  
 public class EmployeeTest  
 {  
   public static void main( String[] args )  
   {  
     Date birth = new Date( 7, 24, 1949 );  
     Date hire = new Date( 3, 12, 1988 );  
     Employee employee = new Employee( "Bob", "Blue", birth, hire );  
     System.out.println( employee );  
   }  // end main  
 }  // end class EmployeeTest  


Senin, 20 Februari 2017

Konsep Pemrograman Berbasis Objek

1. Object
    Object adalah segala sesuatu yang dapat direpresentasikan dengan data pada suatu memori komputer dan dapat dimanipulasi oleh program computer. Objek dapat berupa fisik non-fisik. Objek memiliki 2 komponen, yaitu behavior / method dan attribute / property.
    Contoh: Angka, teks, suara, gambar, video, meja, mobil, dsb.

2. Property
    Property adalah (atau bisa juga disebut attribute) adalah data yang merupakan identitas atau informasi dari suatu yang terdapat dalam sebuah class.
    Contoh: Misal kita mempunyai meja sebagai objek, maka propertynya adalah warna, ukuran, bahan, dsb.

3. Method
    Method (atau bisa juga disebut behavior) adalah tingkah laku atau apa yang dapat dilakukan oleh objek.
    Contoh: Misal kita mempunyai laptop sebagai objek, maka methodnya adalah menghidupkan laptop, mematikan laptop, dsb.

4. Class
    Class adalah kumpulan objek yang mempunyai properties dan methods yang sama. Class digunakan hanya untuk membuat kerangka dasar.
    Contoh: nama_mahasiswa, nrp, tanggal_lahir, dsb.

5. State
    State adalah adalah variabel-variabel yang dideklarasikan di dalam class. 
    Contoh: Member member = new Member();

6. Instance
    Instance adalah setiap copy dari suatu objek yang berasal dari class tertentu.

7. Instantiation
    Instantiation adalah kegiatan untuk membuat copy baru dari suatu objek yang berasal dari class tertentu.

Contoh Implementasi Class (barang):
public class mahasiswa {  
   private String Nrp;  
   private String nama;  
   public String getNama() {         // method berupa Fungsi  
     return nama;  
   }  
   public void setNama(String nama) { // method berupa procedure  
     this.nama = nama;  
   }  
   public String getNrp() {           // method berupa Fungsi  
     return nim;  
   }  
   public void setNim(String nim) {     // method berupa procedure  
     this.nim = nim;  
   }  
 }



Contoh Implementasi Class (menghitung rata-rata):
package latihan;
import java.util.Scanner;
public class scanner_angka {

       public static void main(String[] args) {
              // TODO Auto-generated method stub
             
              int nilai1, nilai2, nilai3;
              double hasil;
             
              Scanner DataIn = new Scanner(System.in);
              System.out.print("Nilai Ujian Ke-1 : ");
              nilai1 = DataIn.nextInt();
             
              System.out.print("Nilai Ujian Ke-2 : ");
              nilai2 = DataIn.nextInt();
             
              System.out.print("Nilai Ujian Ke-3 : ");
              nilai3 = DataIn.nextInt();
             
              hasil = (nilai1+nilai2+nilai3)/3;
             
              System.out.println("Nilai Rata-Rata      : " + hasil);
       }

}