Rabu, 19 Disember 2012

CHAPTER 10 : STREAMS AND FILE I/O

10.1 An overview of streams file i/o

        - We can use file to to store input for a program or to hold output from a program.In java,file i/o,as
           well as simple keyboard and screen i/o.
        - A stream is a flow of data.The data might be character,number, or bytes consisting of binary of
          data .if the data flows into your program,the stream is called an input stream
        - For example,if an input stream is connected to the keyboard,the data flows from the keyboard into
          your program.


   WHY USE FILES FOR I/O

         -The keyboard input and the screen output we have use so far deal with tempory data.When the
           program ends,the data type of keyboard and left on screen go way.files provide you with away to
          to store data permanently.
        -An input file can used over and over again by different programs,without the need to type the data 
          again for each program.files also provided you with convinient way to deal with large quentities\
         of data.


10.2 Text-file i/0

      -The class PrintWriter in java class library defines the metods that we will need to create and write to 
        will need to create and write to a text file.This class is the preferred one for writting to a text file.
      -Before we can write to text file,we must connect it to an output stream.That is,we open the file.
        To do this,we need the name of file as a string.the file has a name like out.

    GOTCHA

    -When you open a text file or a binary file for output,you alwys begins with an empty file.if no existing
      file has the given name,the constructor that you invoke will create an empty file with the name

Appending to a text file

     -We may simply want to add,or append,more data to the end of the file.to append programs output to
       the text file named by the string variable.
     -it's old content will remain,the program's otput will be replaced after those content.but if the files does
       not already exist, java will create an empty file.


10.3 TECHNIQUES FOR ANY FILE

       -The class file provides a way to represent that file in a general way.Astring such as"traesure.txt"
         might be a file name,but it has only string properties, and java does not recognise it as file name.g as
       - Althought some stream classes have constructor that accept a string name of a file,some do not
          some stream clases have constructor that accept only a file object as an argument.we already saw
         in the previious section that when reading a text file,we cannot

CHAPTER 9 : EXCEPTIONS HANDLING


An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:
  • A user has entered invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications, or the JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of exceptions:
  • Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
  • Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
  • Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Exception Hierarchy:

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses : IOException class and RuntimeException Class.
Java Exceptions

Exceptions Methods:

Following is the list of important medthods available in the Throwable class.


SNMethods with Description
1public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3public String toString()
Returns the name of the class concatenated with the result of getMessage()
4public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:


try
{
   //Protected code
}catch(ExceptionName e1)
{
   //Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

Example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.


// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{

   public static void main(String args[]){
      try{
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}
This would produce following result:
Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:


try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

Example:

Here is code segment showing how to use multiple try/catch statements.
try
{
   file = new FileInputStream(fileName);
   x = (byte) file.read();
}catch(IOException i)
{
   i.printStackTrace();
   return -1;
}catch(FileNotFoundException f) //Not valid!
{
   f.printStackTrace();
   return -1;
}

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException:


import java.io.*;
public class className
{
   public void deposit(double amount) throws RemoteException
   {
      // Method implementation
      throw new RemoteException();
   }
   //Remainder of class definition
}

Amethod can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException:


import java.io.*;
public class className
{
   public void withdraw(double amount) throws RemoteException,
                              InsufficientFundsException
   {
       // Method implementation
   }
   //Remainder of class definition
}

The finally Keyword

The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:


try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}finally
{
   //The finally block always executes.
}

Example:

public class ExcepTest{

   public static void main(String args[]){
      int a[] = new int[2];
      try{
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      finally{
         a[0] = 6;
         System.out.println("First element value: " +a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

This would produce following result:


Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Note the followings:
  • A catch clause cannot exist without a try statement.
  • It is not compulsory to have finally clauses when ever a try/catch block is present.
  • The try block cannot be present without either catch clause or finally clause.
  • Any code cannot be present in between the try, catch, finally blocks.

Declaring you own Exception:

You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes:
  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a runtime exception, you need to extend the RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception{
}

You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Example:

// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception
{
   private double amount;
   public InsufficientFundsException(double amount)
   {
      this.amount = amount;
   } 
   public double getAmount()
   {
      return amount;
   }
}

To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.


// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount
{
   private double balance;
   private int number;
   public CheckingAccount(int number)
   {
      this.number = number;
   }
   public void deposit(double amount)
   {
      balance += amount;
   }
   public void withdraw(double amount) throws
                              InsufficientFundsException
   {
      if(amount <= balance)
      {
         balance -= amount;
      }
      else
      {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
   public double getBalance()
   {
      return balance;
   }
   public int getNumber()
   {
      return number;
   }
}

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.


// File Name BankDemo.java
public class BankDemo
{
   public static void main(String [] args)
   {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);
      try
      {
         System.out.println("\nWithdrawing $100...");
         c.withdraw(100.00);
         System.out.println("\nWithdrawing $600...");
         c.withdraw(600.00);
      }catch(InsufficientFundsException e)
      {
         System.out.println("Sorry, but you are short $"
                                  + e.getAmount());
         e.printStackTrace();
      }
    }
}

Compile all the above three files and run BankDemo, this would produce following result:


Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
        at CheckingAccount.withdraw(CheckingAccount.java:25)
        at BankDemo.main(BankDemo.java:13)

Common Exceptions:

In java it is possible to define two catergories of Exceptions and Errors.
  • JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException,
  • Programmatic exceptions . These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException.



BAB 8 – PEWARISAN DAN POLIMORFISMA



3.1            Pengenalan

Pewarisan (inheritance) dan polimorfisma (polymorphism) merupakan dua ciri penting dalam PBO. Dengan menggunakan ciri-ciri ini, tugas menakrif kelas baru atau menambahbaik (ugrade) kelas sedia ada menjadi lebih mudah dan cekap. Bab ini akan melihat bagaimana kedua-dua proses ini boleh diaplikasikan dalam membangunkan aturcara.


3.2            Pewarisan (inheritance)


Pewarisan merujuk kepada proses yang membenarkan sesebuah objek mewarisi sifat dan kelakuan kelas sedia ada.

Dengan pewarisan, sekiranya kita ingin menakrifkan suatu kelas baru, yang mana sebahagian dari sifat dan kelakuannya sudah pun ditakrifkan dalam kelas lain yang sedia ada, maka kita boleh tetapkan supaya kelas baru tersebut ‘mewarisi’ sifat dan kelakuan kelas sedia ada tersebut. Dengan itu, semua sifat (pembolehubah) dan kelakuan yang ditakrifkan dalam kelas sedia ada tersebut akan wujud secara automatik di dalam kelas baru, tanpa perlu ditakrifkan semula di dalam kelas baru tersebut. Jadi, tak perlulah kita bersusah payah mencipta kelas baru tersebut dari awal!

Sebagi contoh, katakan kita telah sedia ada kelas Bulatan yang telah ditakrifkan mempunyai sifat: jejari, serta mempunyai kelakuan luas(). Katakan sekarang kita ingin bangunkan pula kelas Sfera dengan sifat: jejari, dan kelakuan luas() dan isipadu(). Jika diamati, sifat jejari dan kelakuan luas() dari kelas Sfera lebih kurang serupa fungsinya dengan pembolehubah jejari dan kelakuan luas() yang telah ditakrifkan dalam kelas Bulatan. Dengan itu, sekarang ini kita ada dua pilihan: menakrifkan semula kelas Sfera (seperti Rajah 3-1(a) ) atau kita boleh takrifkan kelas Sfera sebagai waris kepada kelas Bulatan (rujuk Rajah 3-1(b) ). Jika kita pilih pilihan pertama, kita perlu bina kelas Sfera dari awal!. Sebaliknya, jika kita pilih pilihan kedua, kita tidak perlu meakrifkan kelas Sfera dari awal. Sebaliknya, kita hanya perlu menambah dan mengubahsuai sahaja kelas Bulatan. Jadi lebih baik kita pilih pilihan kedua iaitu dengan menakrifkan kelas Sfera sebagai waris kepada kelas Bulatan . Dengan ini, kelas Sfera tidak perlu lagi ditakrifkan dengan pembolehubah jejari dan kelakuan luas() kerana ia akan wujud secara automatik, hasil dari pewarisan itu. jadi, kita hanya perlu tambahkan satu kelakuan baru dalam kelas Sfera iaitu isipadu().

3.2.1        Superkelas dan subkelas

Suatu kelas yang mewariskan sifat dan kelakuannya kepada suatu kelas lain dipanggil superkelas (superclass) atau kelas ibubapa (parent), dan kelas yang mewarisi sifat dan kelakuan dari kelas yang lain dipanggil subkelas (subclassatau kelas anak (child).


Hubungan pewarisan merupakan suatu hubungan berhierarki di antara kelas. Sebagai contoh, pada Rajah 3-3, kelas Geometri mempunyai 2 subkelas iaitu Bulatan dan Segiempat. Jadi, kita katakan Geometri adalah superkelas kepada kelas Bulatan dan Segiempat. Sementara itu, kelas Sfera pula adalah subkelas kepada kelas Bulatan. Maka, kita katakan pula Bulatan adalah superkelas bagi kelas Sfera.


Hubungan antara subkelas dan superkelas juga boleh dilihat sebagai hubungan ‘adalah suatu’ (‘is-a’ relationship). Misalnya, kita katakan Bulatan adalah suatu Geometri (Bulatan is-a Geometri). Begitu juga, Sfera adalah suatu Bulatan (Sfera is-a Bulatan).


3.2.2        Konsep pewarisan tunggal

Java hanya membenarkan pewarisan tunggal (single inheritance) sahaja, bermakna satu kelas hanya boleh mewarisi sifat dan kelakuan dari satu kelas sahaja. Ini bagi mengelakkan kekeliruan yang timbul akibat pewarisan berbilang (multiple inheritance). Sesetangah bahasa pengaturcaraan seperti C++, membenarkan pewarisan berbilang iaitu satu kelas boleh mewarisi sifat dan kelakuan dari lebih dari satu kelas. Rajah 3-4(a) dan Rajah 3-4(b) menjelaskan perbezaan antara pewarisan tunggal dan pewarisan berbilang. Dalam Rajah 3-4(a) kelas Sfera hanya mempunyai satu superkelas sahaja iaitu Bulatan. Begitu juga kelas Bulatan ada hanya satu superkelas sahaja iaitu Geometri. Jadi kedua-dua hubungan pewarisan ini adalah hubungan pewarisan tunggal. Sementara itu, dalam Rajah 3-4(b), kelas Selinder mempunyai 2 superkelas, iaitu Segiempat dan Bulatan. Jadi kelas Selinder mengamalkan pewarisan berbilang.


3.3            Polimorfisma (Polymorphism)

Secara umum, polimorfisma adalah proses menakrifkan dua atau lebih kelakuan yang sama namanya tetapi melakukan tugas-tugas yang berbeza. Dalam Java, polimorfisma boleh diaplikasikan dalam dua keadaan: oeverloading dan overriding.


3.3.1        Overloading

Overloading merujuk kepada proses menakrif satu atau lebih kelakuan (atau konstruktur) dengan nama yang sama dalam satu kelas yang sama, tetapi setiap satu kelakuan tersebut akan bertindak dengan cara yang berbeza.

Sebagai contoh, kelas Bulatan boleh ditakrifkan seperti berikut:

class Bulatan
{
     public double jejari;

     // kelakuan luas() pertama
public double luas()
     {
           return (Math.PI * jejari * jejari);
     }

     // kelakuan luas() kedua
     public double luas(double rad)
     {
           jejari = rad;
           return (Math.PI * jejari * jejari);
     }
}

Dalam kelas Bulatan ini, terdapat dua kelakuan luas() yang setiap satunya akan melaksanakan tugas yang berbeza. Maknanya, kita telah di-‘overload’-kan kelakuan luas()

Kita boleh gunakan kelas Bulatan ini seperti berikut:

Bulatan b1 = new Bulatan(); 
Bulatan b2 = new Bulatan(); 

b1.jejari = 2.5;
System.out.println(“Luas: “ + b1.luas());   // guna luas() pertama

System.out.println(“Luas: “ + b2.luas(3.0)); // guna luas() kedua

Walaupun kelakuan yang dioverload boleh mempunyai nama yang sama, tetapi kedua-dua kelakuan tersebut mestilah mempunyai tandatangan (signature) yang berbeza. Tandatangan kelakuan ditentukan oleh jenis, bilangan dan susunan parameternya.

Contohnya, tiga kelakuan berikut mempunyai tandatangan yang berlainan:

public void myMethodA(int a)
{
     :
}

public void myMethodA(int a, double b)
{
     :
}

public void myMethodA(double a, int b)
{
     :
}


Sementara, dua kelakuan berikut, sebenarnya mempunyai tandatangan yang sama:

public void myMethodB(int a)
{
     :
}

public int myMethodB(int x)  // parameter sama jenis
{
     :
}

Begitu juga dengan dua kelakuan berikut, masing-masing mempunyai tandatangan yang sama

public double myMethodC(double a, int b)
{
     :
}

public double myMethodC(double b, int a)  // parameter sama susunan
{
     :
}


Oleh itu, kita perlu pastikan agar kelakuan yang ingin dioverload perlu mempunyai tandatangan yang berbeza. Jika tidak, kita akan mendapat ralat semasa proses mengompil.


3.3.2        Overriding

Proses overriding berlaku apabila suatu kelas yang mewarisi suatu kelakuan dari kelas lain mengubahsuai kelakuan yang diwarisinya itu.

Kadangkala kelakuan yang diwarisi perlu diperbaiki, supaya ia sesuai digunakan di dalam kelas yang mewarisinya. Sebagai contoh, jika kelas Sfera mewarisi kelas Bulatan, maka kelas Sfera akan mewarisi kelakuan luas() dari kelas Bulatan tersebut. Bagaimanapun, kelakuan luas() yang ditakrifkan dalam kelas Bulatan menggunakan formula pengiraan yang tidak sama dengan kelakuan luas() bagi kelas Sfera. Jadi, kelas Sfera perlu override kelakuan luas() yang diwarisinya itu supaya ia menggunakan formula yang lebih sesuai dengan kelas Sfera.

Tidak seperti proses overloading, kelakuan yang akan override kelakuan yang diwarisi mestilah mempunyai tandatangan yang serupa dengan kelakuan yang ingin dioveride tersebut. Jika tidak, kelakuan yang diwarisi itu tidak akan di override.


3.3.3        Perbezaan antara overloading dan overriding

Perbezaan antara overloading dan overriding ditunjukkan secara ringkas di dalam Jadual 3-1

Jadual 3-1: Perbezaan antara overloading dan overriding
Konsep
Definisi
Keterangan lengkap
Overloading
Lebih daripada satu kelakuan dengan nama yang sama dalam kelas  yang sama
Tandatangan bagi setiap kelakuan adalah berbeza

Overriding
Mengubahsuai kelakuan yang diwarisi dari  superkelas dengan perlaksanaan yang sesuai dengan subkelas tersebut
Kedua-dua kelakuan mesti mempunyai tandatangan yang sama



3.4            Menakrifkan kelas dengan pewarisan dan polimorfisma


Katakan kita ingin bangunkan aturcara untuk digunakan di sebuah kedai video. Jadi, untuk melaksanakan tugas ini, salah satu kelas penting yang perlu ditakrifkan dahulu adalah kelas VideoTape.

Setelah mengkaji, kita telah membuat keputusan untuk menakrifkan kelas VideoTape dengan spesifikasi seperti berikut:

Kelas: VideoTape.java

Sifat
Kegunaan / fungsi
Jenis
- title
Menyimpan tajuk video
String
- length
Meyimpan jumlah masa tayangan video(dalam minit).
int
- avail
Menentukan sama ada video tersebut telah disewa (tiada di dalam kedai) atau belum disewa (ada didalam kedai).
boolean

Kelakuan
Fungsi
Jenis
+ Video(ttl, lgth)
Konstruktor yang akan menetapkan nilai bagi title (melalui ttl) dan length (lgth) bagi satu objek VideoTape yang baru. Nilai avail pula akan ditetapkan terus (tanpa ambil nilai dari parameter) sebagai true.
-
+ show()
Kelakuan yang akan memaparkan nilai-nilai titlelength dan avail bagi sesuatu objek VideoTape.
void

Dari spesifikasi ini, kita bangunkan kelas VideoTape seperti berikut:

class VideoTape
{
     protected String title;
     protected int length;
     protected boolean avail;

  
     public VideoTape(String ttl, int lngth)
     {
           title = ttl;
           length = lngth;
           avail = true;
     }

     public void show()
     {
           System.out.println(“\nTajuk        : " + title);
           System.out.println(“Jangkamasa   : " + length + “ min.");
           System.out.println(“Belum disewa : "  + avail);
     }
}

Bagi menguji kelas VideoTape ini, kita bangunkan kelas berikut:


class TapeStore {
     public static void main ( String args[] ) {
           VideoTape item1 = new VideoTape("Jaws", 120);
           VideoTape item2 = new VideoTape("Star Wars", 160);
           item1.show();
           item2.show();
     }
}

Hasil output bagi kelas TapeStore adalah seperti berikut:

Tajuk        : Jaws
Jangkamasa   : 120 min.
Belum disewa : true

Tajuk        : Star Wars
Jangkamasa   : 160 min.
Belum disewa : true

Selepas beberapa hari, kita dapati kebanyakan pita video mempunyai masa tayangan yang sama, iaitu 120 minit. Jadi, untuk memudahkan tugas meincipta objek VideoTape yang baru, kita putuskan untuk overloadkan konstruktor supaya konstruktor baru ini akan menetapkan masa tayangan kepada 120 secara automatik. Jadi, kelas VideoTape yang telah dikemaskini akan jadi seperti berikut:

public class VideoTape
{
     String title;
     int length;
     boolean avail;

  
     public VideoTape(String ttl, int lngth)
     {
           title = ttl;
           length = lngth;
           avail = true;
     }

     public VideoTape(String ttl)
     {
           title = ttl;
           length = 120;
           avail = true;
     }

     public void show()
     {
           System.out.println(“\nTajuk        : " + title);
           System.out.println(“Jangkamasa   : " + length + “ min.");
           System.out.println(“Belum disewa : "  + avail);
     }
}

Jadi
, menggunakan kelas VideoTape yang baru ini, kita boleh bina objek VideoTape dengan 2 cara yang berbeza seperti berikut:

class TapeStore  {
     public static void main ( String args[] )       {
           VideoTape item1 = new VideoTape("Jaws");
           VideoTape item2 = new VideoTape("Star Wars", 160);
           item1.show();
           item2.show();
     }
}

Hasil output bagi kelas TapeStore sekarang adalah seperti berikut:

Tajuk        : Jaws
Jangkamasa   : 120 min.
Belum disewa : true

Tajuk        : Star Wars
Jangkamasa   : 160 min.
Belum disewa : true

Katakan pula selepas beberapa hari, kita dapati adalah penting untuk memasukkan nama pengarah dan rating (U, 18SG, 18SX, 18PA atau 18PL) bagi pita-pita video cereka (movie). Bagaimanapun, di dalam kedai video, terdapat juga pita-pita dokumentari, konsert dan sebagainya yang tak perlukan nama pengarah dan rating. Jadi kita tidak boleh dengan mudah mengubahsuai kelas VideoTape. Cara yang paling berkesan ialah dengan mendefinisi kelas baru khas untuk pita-pita video cereka. Kita namakan kelas ini sebagai MovieTape.

Kelas MovieTape ada persamaan dengan kelas VideoTape, tetapi dengan sedikit penambahan dan pengubahsuaian. Jadi kita putuskan untuk menakrif kelas MovieTape sebagai mewarisi kelas VideoTape. Jadi kelas MovieTape akan ditakrifkan seperti berikut:

class MovieTape extends VideoTape
{
     protected String director;
     protected String rating;
    
     public MovieTape(String ttl, int lngth, String dir, String rt)
     {
           super(ttl, lngth);
           director = dir;
           rating = rt;
     }

     public MovieTape(String ttl, String dir, String rt)
     {
           super(ttl);
           director = dir;
           rating = rt;
     }

     // override kelakuan show() dari kelas VideoTape
     public void show()
     {
           super.show();
           System.out.println(“Pengarah     : "  + director);
           System.out.println(“Spesifikasi  : "  + rating);
     }
}

Dalam kelas MovieTape ini, terdapat 2 perkara baru: katakunci extends dan super
3.4.1        Katakunci extends

Kelas MovieTape menggunakan katakunci extends pada pengepala kelasnya. Katakunci extends ini adalah katakunci yang perlu diletakkan bagi menyatakan bahawa MovieTape adalah mewarisi kelas VideoTape.


3.4.2        Konstruktor bagi subkelas dan kelakuan super()

Oleh kerana MovieTape adalah subkelas kepada VideoTape, maka semua pembolehubah dan kelakuan VideoTape akan wujud secara automatik di dalam kelas MovieTape. Bagaimanapun, terdapat pengecualian dalam peraturan ini bagi konstruktor. Konstruktor bagi superkelas tidak akan diwarisi oleh subkelas. Oleh itu konstruktor bagi kelas MovieTape perlu ditakrifkan semula. 

Untuk mencapai konstruktor bagi superkelas, kita boleh gunakan kelakuan khas dipanggil super(). Kelakuan super() membolehkan konstruktor bagi superkelas dicapai oleh konstruktor bagi subkelas. Jadi pernyataan

super(ttl, lngth);

dalam konstruktor pertama bagi kelas MovieTape akan memanggil dan melaksanakan konstruktor pertama bagi kelas VideoTape. Begitu juga, pernyataan

super(ttl);

dalam konstruktor kedua bagi kelas MovieTape akan memanggil dan melaksanakan konstruktor kedua bagi kelas VideoTape.

Semasa menggunakan kelakuan super(), fakta-fakta berikut perlu diambil perhatian:
·                Ia membolehkan capaian kepada konstruktor superkelas
·                Ia hanya boleh dicapai di dalam konstruktor bagi subkelas.
·                Menggunakan super() dalam konstruktor subkelas adalah suatu pilihan sahaja, bukan kemestian
·                Jika menggunakan super(), ia mesti diletakkan pada permulaan baris dalam badan konstruktor subkelas.
·                Jika super() tidak digunakan dalam konstruktor subkelas, Java tetap akan melaksanakan konstruktor default bagi superkelas setiap kali objek baru subkelas dicipta.


3.4.3        Override kelakuan dan penggunaan katakunci super

Selain konstruktor, kita juga perlu override kelakuan show() kerana kelakuan show() yang diwarisi hanya akan memaparkan titlelength dan avail sahaja, sedangkan kelas MovieTape ada pembolehubah director dan rating yang juga perlu dipaparkan. Walaupun begitu, kelakuan show() yang ditakrifkan dalam kelas VideoTape masih lagi boleh digunakan. Untuk laksanakan kelakuan show() dalam kelas VideoTape (superkelas) di dalam kelas MovieTape, kita perlu gunakan katakunci super. Katakunci super adalah ganti nama bagi membolehkan kita merujuk superkelas bagi sesuatu subkelas. Jadi, pernyataan

super.show();

dalam kelakuan show() bagi kelas MovieTape akan memanggil kelakuan show() dalam superkelas bagi MovieTape iaitu kelas VideoTape.

Catatan:
Kita perlu faham perbezaan antara kelakuan super() dan katakunci super:
·                super() – merujuk kepada konstruktor pada superkelas
·                super.namaKelakuan() – merujuk kepada kelakuan yang berada dalam superkelas
·                super.namaPembolehubah – merujuk kepada pembolehubah yang berada dalam superkelas

Related Posts Plugin for WordPress, Blogger...