Anda di halaman 1dari 23

BAHAGIAN PENDIDIKAN TEKNIK DAN

VOKASIONAL
KEMENTERIAN PENDIDIKAN MALAYSIA
ARAS 5 & 6, BLOK E14, KOMPLEKS E,
PUSAT PENTADBIRAN KERAJAAN PERSEKUTUAN

KERTAS PENERANGAN
(INFORMATION SHEET)

KOD DAN NAMA


IT-030-4:2013 COMPUTER NETWORK ADMINISTRATION
PROGRAM

TAHAP DAN SEMESTER 4 (SEMESTER 1)

KOD DAN TAJUK


DKB 4333 PROGRAMMING LANGUAGE
KURSUS

K1 INTRODUCTION TO LATEST PROGRAMMING


LANGUAGE
NO.DAN TAJUK K2 DATA TYPES, VARIABLE AND OPERATORS,
KOMPETENSI CONTROL STATEMENTS AND METHOD
K3 BASIC OF ARRAY, STRING MANIPULATION AND
CLASSES

NO. KOD KSKV DKB4333 / KP(3/3) Muka Surat : 1 Drpd : 23

NO. KOD NOSS DKB4333 / KP(3/3)

TAJUK/TITLE :
BASIC OF ARRAY, STRING MANIPULATION AND CLASSES

TUJUAN / PURPOSE :
Kertas penerangan ini adalah bertujuan menerangkan mengenai :
 menerangkan mengenai konsep tatasusunan (array)
 menerangkan mengenai tatasusunan satu dimensi (One-Dimensional Array)
 menerangkan mengenai tatasusunan dua dimensi (Two-Dimensional Array)
 menerangkan mengenai string declaration
 menerangkan mengenai string function
 menerangkan sintaksis untuk mencipta kelas
 menerangkan sintaksis untuk mencipta objek
 menerangkan sintaksis untuk ’Method Call by Value and Reference’
 menerangkan sintaksis untuk ’Overriding and Overloading’
Muka Surat / Page : 2
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

PENERANGAN / INFORMATION :

1. Array Fundamentals

a) Apakah itu tatasusunan?


• Satu struktur data mudah yg digunakan utk :
 Menyimpan sekumpulan data yang terdiri daripada jenis yang sama
 Menggunakan satu pembolehubah sahaja untuk dirujuk.

2. Tatasusunan satu dimensi (One Dimensional Array)

• terdiri dari satu baris dan beberapa lajur


x[0] x[1] x[2] x[3]

80 90 100 70
1 baris

beberapa lajur

a) Mengisytihar dan memberi nilai awal ke dalam tatasusunan satu dimensi

Syntax :
<jenis data> <pembolehubah>[ ] ={ nilai1, nilai2, nilai3 };

Example :
int markah[ ] = {80, 88, 90, 60};

>> Rujuk Latihan 1 dan Latihan 2

b) Mengisytihar tatasusunan satu dimensi

Syntax :
<jenis data> <pembolehubah>[ ] = new <jenis data> [saiz tatasusunan];

Contoh :
int markah[ ] = new int[4];

>> Rujuk Latihan 3 dan Latihan 4

c) Merujuk elemen dalam tatasusunan

i) Elemen pertama :

System.out.println(“Markah = “+markah[0]);

ii) Elemen terakhir (saiz – 1)

System.out.println(“Markah = “+markah[3]); //jika saiz = 4


Muka Surat / Page : 3
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

iii) Memaparkan semua elemen dalam tatasusunan

for (k=0; k<4; k++) /* for (k=0; k<=3; k++) */


{
System.out.println(“Markah = “+markah[k]);
}

d) Memasukkan data ke dalam tatasusunan

Contoh 1 : memasukkan data jenis String

String name[ ]=new String[4];

for (k=0; k<4; k++) /* array name of size 4 */


{
System.out.println(“Enter name :“);
name[k] = stdin.readLine();
}

Contoh 2 : memasukkan data jenis Int

int markah[]=new int[4];

for (k=0; k<4; k++) /* array markah of size 4 */


{
System.out.println(“Enter marks :“);
str = stdin.readLine();
markah[k]=Integer.parseInt(str);
}

Contoh aturcara tatasusunan satu dimensi :

Tulis satu aturcara untuk menerima nama dan berat 5 orang pelajar dan menyimpan data
tersebut ke dalam dua tatasusunan yang berlainan. Paparkan data tersebut di akhir program,.

import java.io.*;
class Pelajar
{
public static void main (String args[]) throws IOException
{
BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
int j;
String str;
String name[]= new String[5];
double weight[]=new double[5];

/*** menerima serta menyimpan nama dan berat 5 orang pelajar ke dalam
tatasusunan ***/

for (j=0; j<5; j++) // atau (j<=4)


{
System.out.print("Enter name:");
name[j] = stdin.readLine();

System.out.print("Enter weight:");
str = stdin.readLine();
weight[j] = Double.parseDouble(str);
Muka Surat / Page : 4
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

} //end for

/*** memaparkan nama dan berat 5 orang pelajar ***/

for (j=0; j<5; j++)


{
System.out.println("\nName : "+name[j]);
System.out.println("Weight: "+weight[j]+" kg");
} //end for
} //end of public static void main
} //end of class

3. Tatasusunan dua dimensi (Two Dimensional Array)

• terdiri dari beberapa baris dan beberapa lajur

Baris 0 80 88 90

Baris 1 60 70 95

Baris 2 55 45 35

Baris 3 100 90 80

Lajur 0 Lajur 1 Lajur 2

a) Mengisytihar dan memberi nilai awal ke dalam tatasusunan dua dimensi

Example :
Lajur 0

int markah[ ][ ] = {{80, 88,90}, {60, 70, 95}, {55, 45, 35},{100, 90, 80 }};

Baris 0

Baris 0 Ahmad Aminah

Baris 1 Hana Hashim

Baris 2 Fiqa Fikri

Lajur 0 Lajur 1

String nama[ ][ ] = {{"Ahmad", "Aminah"}, {"Hana", "Hashim"}, {"Fiqa", "Fikri"}};

Baris 0
Muka Surat / Page : 5
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

b) Mengisytihar tatasusunan dua dimensi

Syntax :
<jenis data> <pembolehubah>[ ][ ]= new <jenis data> [baris][lajur]

Contoh :
int markah[ ][ ] = new int[4][3];
String nama[ ][ ] = new String[3][2];

c) Memaparkan semua elemen dalam tatasusunan

for (r=0; r<4; r++) /* Baris : for (r=0; r<=3; r++) */


{
for (c=0; c<3; c++) /* Lajur : for (c=0;c<=2; c++) */
{
System.out.println(“Markah = “+markah[r][c]);
}
}

d) Memasukkan data ke dalam tatasusunan

Contoh 2 : memasukkan data jenis String

String nama[ ][ ]=new String[3][2];


int r, c;

for (r=0; r<3; r++) /* Baris : for (r=0; r<=2; r++) */


{
for (c=0; c<2; c++) /* Lajur : for (c=0;c<=1; c++) */
{
System.out.println(“Masukkan nama :“);
nama[r][c] = stdin.readLine();
}

Contoh aturcara :

import java.io.*;
class PelajarKelas
{
public static void main (String args[]) throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
int j;
String nama[ ][ ]=new String[3][2];
int r, c;

/*** menerima serta menyimpan nama 2 orang pelajar


dari 3 kelas berlainan ke dalam tatasusunan ***/

for (r=0; r<3; r++) /* Baris- kelas: for (r=0; r<=2; r++) */
{
System.out.println("Kelas = "+(r+1));
for (c=0; c<2; c++) /* Lajur- nama: for (c=0;c<=1; c++) */
{
System.out.print("Masukkan nama :");
nama[r][c] = stdin.readLine();
Muka Surat / Page : 6
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

}
}

/*** memaparkan nama pelajar dari 3 kelas***/

for (r=0; r<3; r++) /* Baris- kelas: for (r=0; r<=2; r++) */
{
System.out.println("Kelas : "+(r+1));
for (c=0; c<2; c++) /* Lajur- nama:for (c=0;c<=1; c++) */
{
System.out.println("Nama : "+nama[r][c]);
} //end for
}
} //end of public static void main
} //end of class

Soalan Latihan

1) Isytiharkan tatasusunan satu dimensi dan beri nilai awal berat 5 orang pelajar (Berat :
45.5, 65.3, 65.6, 58.5, 80.6).

2) Isytiharkan tatasusunan satu dimensi dan beri nilai awal gred yang dicapai oleh 4 orang
pelajar bagi modul 1 (Gred : A, E, B, C).

3) Isytiharkan tatasusunan satu dimensi yang bersaiz 3 untuk menyimpan jumlah wang yang
dibelanjakan setiap hari.

4) Isytiharkan tatasusunan satu dimensi yang bersaiz 8 untuk menyimpan aksara yang
mewakili bangsa seseorang (contoh : M, C, I, L).

5) Isytiharkan tatasusunan dua dimensi dan beri nilai awal perbelanjaan harian 3 orang
selama 5 hari.

6) Isytiharkan tatasusunan dua dimensi yang terdiri dari 5 baris dan 4 lajur untuk
menyimpan jumlah wang yang dibelanjakan setiap hari.
Muka Surat / Page : 7
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

STRING DECLARATION
String merupakan satu urutan aksara.
Menggunakan kelas String, nilai awal bagi text boleh dibuat secara terus.

Contoh :

String text = “I CAN WRITE A GOOD PROGRAM IN JAVA”;

Kelas String boleh digunakan untuk manipulasi teks seperti membandingkan teks, mencantum
teks dan sebagainya.
Java menyediakan dua jenis kelas untuk manipulasi teks :

1. String class
2. StringBuffer class

Creating String Objects Using String Class

1. To Create An Empty String Object


e.g :

class Msg
{
public static void main(String arg[])
{
String message = new String();
System.out.println(message);
}
}

2. To Create A String Object Initialized With An Array Of Characters


e.g :

class HelloString
{
public static void main(String arg[])
{
char hello[]= {'H','E', 'L', 'L', 'O'};
String message=new String(hello);
System.out.println(message); //print a String object name
}
}

3. To Create A String Object That Contains The Same Character Sequence As Another Object
e.g :

class HelloString
{
public static void main(String arg[])
{
char hello[]= {'H','E', 'L', 'L', 'O'};
String message=new String(hello);
String message2=new String(message); // Create A String Object
That Contains The Same Character Sequence as Another Object
System.out.println(“message 1”+message);
System.out.println(“message 2”+message2);
}
}
Muka Surat / Page : 8
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

4. To Create A String Object using a string literal

e.g :
String hobi =”Membaca novel”;
System.out.println("Hobi - "+hobi);

STRING FUNCTIONS

1. length() – to find the number of characters in a string

class Lengthstr
{
public static void main(String args[])
{
String msg = “Please keep our room clean and tidy”;
int numchar = msg.length();
System.out.println(“Number of character = “+numchar);
}
}

2. concat() – to combine two strings

String first = “Kolej Vokasional Perdagangan”;


String second = “ Johor Bahru”;
String cantum = first.concat(second);
System.out.println(cantum);

3. charAt() – to extract a single character from a string

String state = “Johor”;


char ch_state = state.charAt(2); J o h o r
System.out.println(ch_state);

0 1 2 3 4 index

4. equals() – to compare two strings for equality

String name1 = “Muhammad”;


String name2 = “Muhammad”;
String name3 = “Muhamad”;
if (name1.equals(name2))
System.out.println(name1+ " is equal to"+ name2);
else
System.out.println(name1+ " is not equal to "+ name2);

5. indexOf() – to search the first occurrence of a character inside a string - return


value of index of type integer
0 1 2 3 4 5 6 7 8 9 10 11 12 13 INDEX
T H I S I S A T E S T

String testing = “THIS IS A TEST”;


int index_s = testing.indexOf(‘S’);
System.out.println(“Index of character S = “+index_s);
int index_is = testing.indexOf(“IS”);
System.out.println(“Index of string IS = “+index_is);
Muka Surat / Page : 9
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

6. lastIndexOf() – to search the last occurrence of a character inside a string - return


value of index of type integer

e.g :
String testing = “THIS IS A TEST”;
int lastindex_s = testing.lastIndexOf(‘S’);
System.out.println(“Last Index of character S = “+lastindex_s);

7. replace() – to replace all occurrences of a character in a string with another


character

e.g :
String msg = “Thif if a teft”; f – original
String msg2 = msg.replace(‘f’, ‘s’); s - replace
System.out.println(“Old String = “+msg);
System.out.println(“New String = “+msg2);

8. trim() – to trim the leading and trailing white spaces in a string - Trimchar

e.g:
String hello=” Hello Malaysia “;
String hello2=hello.trim();
System.out.println(“hello = “ +hello);
System.out.println(“hello2 = “ +hello2);

9. toLowerCase() – to convert to lower case

e.g:
String name=”MUHAMMAD”;
String name2=name. toLowerCase();
System.out.println(“name = “ +name);
System.out.println(“name2 = “ +name2);

10. toUpperCase() – to convert to upper case

e.g:
String name3="aminah";
String name4=name. toUpperCase();
System.out.println("\nnama = " +name3);
System.out.println("nama2 = " +name4);

11. substring() – to extract a part of string, based on the range of index

0 1 2 3 4 5 6 7 8 9 10 11 12 13 INDEX
T H I S I S A T E S T
e.g:

String testing = “THIS IS A TEST”; start index =8


String subtest=testing.substring(8,13); last index -1 =13-1 = 12
System.out.println("\nSubstring = " +subtest);
Muka Surat / Page : 10
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

Soalan Latihan :

1. Namakan string function yang digunakan untuk mencari panjang teks.


2. Namakan string function yang digunakan untuk mencantumkan dua teks menjadi teks
yang baru
3. Namakan string function yang digunakan untuk membandingkan sama ada dua teks
adalah sama.
4. Namakan string function yang digunakan untuk menukarkan aksara dari huruf kecil ke
huruf besar.
5. Namakan string function yang digunakan untuk menukarkan aksara dari huruf besar ke
huruf kecil.

3.3.1 Creating a Class

Apakah kelas?
 Kelas merupakan templat/blueprint yang digunakan untuk mencipta objek.
 Kelas mewakili objek dan set operasi yang boleh diaplikasikan untuk objek tersebut.

Mencipta kelas :

public class class_name


{
Data members;
Methods;
}

Contoh 1:

public class Car


{
public:
double color; //color of a car
double model; //model of a car
}

Contoh 2:
public class Dog
{
String breed;
int ageC;
String color;

void barking() {
}

void hungry() {
}

void sleeping() {
}
}
Muka Surat / Page : 11
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

 Kelas terdiri daripada data members dan method.


 Data members boleh terdiri daripada mana-mana jenis pemboleh ubah berikut:
 Local variables − Variables defined inside methods, constructors or
blocks are called local variables. The variable will be declared and
initialized within the method and the variable will be destroyed when
the method has completed.
 Instance variables − Instance variables are variables within a class
but outside any method. These variables are initialized when the
class is instantiated. Instance variables can be accessed from inside
any method, constructor or blocks of that particular class.
 Class variables − Class variables are variables declared within a
class, outside any method, with the static keyword.
 Kelas boleh mengandungi seberapa banyak method untuk mengakses nilai pada
method yang lain. Dalam contoh di atas, barking(), hungry() dan sleping() adalah
method.
 Dalam Java, nama kelas mewakilkan nama fail bagi kod program dan ia bersifat
case senstive.

 Public, private dan protected dipanggil label penglihatan (visibility labels).


 Private – members yang diisytiharkan sebagai private hanya boleh dicapai
dari dalam kelas sahaja.
 Public – members boleh dicapai dari dalam atau luar kelas.

Constructor

Apabila membincangkan tentang kelas, salah satu topik sub yang paling penting ialah
constructor. Setiap kelas mempunyai constructor. Jika kita tidak menulis constructor untuk
kelas, pengkompil Java akan membina constructor lalai untuk kelas itu.

Definisi: Constructor merupakan satu method yang membolehkan objek memberi nilai awal
kepada dirinya sendiri semasa ia dicipta.

Contoh constructor:

public class Puppy


{
public Puppy() {
}
public Puppy(String name) {
//konstruktor ini mempunyai satu parameter iaitu
name
}
}

Antara ciri-ciri constructor ialah:


1. Constructor mempunyai nama yang sama dengan nama kelasnya. 2. They do not return
any value.
3. Sintaks untuk constructor adalah sama dengan sintaks method.
4. Apabila kita mendefinisikan constructor, ia akan dipanggil secara automatik semasa objek
dicipta sebelum operator yang lain melengkapkan tugasnya.
5. Java akan mencipta constructor lalai jika anda tidak mendefinisi contructor.
Muka Surat / Page : 12
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

3.3.2 Creating an Object

 Objek dicipta daripada kelas. Dalam java, kita menggunakan katakunci new untuk
mencipta objek.
 Terdapat tiga langkah untuk mencipta objek daripada kelas:
 Declaration : Pengisytiharan pembolehubah dengan nama dan jenis objek.
 Instantiation : Katakunci new digunakan untuk mencipta objek’
 Initialization : Katakunci new diikuti dengan panggilan kepada constructor.
Panggilan ini akan memberikan nilai awal kepada objek baru.
 Contoh :

public class Puppy


{
public Puppy(String name) {

//konstruktor ini mempunyai satu parameter iaitu


name
System.out.println(“Passed Name is :” + name
);
}

Public static void main (String [] args) {


Puppy myPuppy = new Puppy (“Tommy”);
}
}

Output :

Passed Name is : Tommy

3.3.3 Method Call by Value and Reference

Contoh ini menerangkan bagaimana untuk mengakses instance variables dan method di
dalam kelas.
Muka Surat / Page : 13
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

public class Puppy {


int puppyAge;

public Puppy(String name) {


// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}

public void setAge( int age ) {


puppyAge = age;
}

public int getAge( ) {


System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}

public static void main(String []args) {


/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */


myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
Muka Surat / Page : 14
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

3.3.4 Overriding and Overloading

OVERLOADING

Method Overloading is a feature that allows a class to have two or more methods having same
name, if their argument lists are different.

Argument lists could differ in –


1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters.

Method overloading is also known as Static Polymorphism.

Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding
where binding of method call to its definition happens at Compile time.

Method Overloading examples:

As discussed above, method overloading can be done by having different argument list. Lets
see examples of each and every case.

Example 1: Overloading – Different Number of parameters in argument list

When methods name are same but number of arguments are different.

class DisplayOverloading
{ public void disp(char c) {
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
Muka Surat / Page : 15
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:

a
a 10

In the above example – method disp() has been overloaded based on the number of arguments
– We have two definition of method disp(), one with one argument and another with two
arguments.

Example 2: Overloading – Difference in data type of arguments

In this example, method disp() is overloaded based on the data type of arguments – Like
example 1 here also, we have two definition of method disp(), one with char argument and
another with int argument.

class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(int c)
{
System.out.println(c );
}
}
Muka Surat / Page : 16
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
Output:

a
5

Example3: Overloading – Sequence of data type of arguments

Here method disp() is overloaded based on sequence of data type of arguments – Both the
methods have different sequence of data type in argument list. First method is having argument
list as (char, int) and second is having (int, char). Since the sequence is different, the method
can be overloaded without any issues.

class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
System.out.println("I’m the second definition of method disp"
);
}
}
class Sample3
{
Muka Surat / Page : 17
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

public static void main(String args[])


{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
Output:

I’m the first definition of method disp


I’m the second definition of method disp

Lets see few Valid/invalid cases of method overloading

Case 1:

int mymethod(int a, int b, float c)


int mymethod(int var1, int var2, float var3)
Result: Compile time error. Argument lists are exactly same. Both methods are having same
number, data types and same sequence of data types in arguments.

Case 2:

int mymethod(int a, int b)


int mymethod(float var1, float var2)
Result: Perfectly fine. Valid case for overloading. Here data types of arguments are different.

Case 3:

int mymethod(int a, int b)


int mymethod(int num)
Result: Perfectly fine. Valid case for overloading. Here number of arguments are different.
Muka Surat / Page : 18
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

Case 4:

float mymethod(int a, float b)


float mymethod(float var1, int var2)
Result: Perfectly fine. Valid case for overloading. Sequence of the data types are different, first
method is having (int, float) and second is having (float, int).

Case 5:

int mymethod(int a, int b)


float mymethod(int var1, int var2)
Result: Compile time error. Argument lists are exactly same. Even though return type of
methods are different, it is not a valid case. Since return type of method doesn’t matter while
overloading a method.

Guess the answers before checking it at the end of programs:

Question 1 – return type, method name and argument list same.

class Demo
{
public int myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample4
{
public static void main(String args[])
{
Demo obj1= new Demo();
obj1.myMethod(10,10);
obj1.myMethod(20,12);
}
}
Muka Surat / Page : 19
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
Answer:
It will throw a compilation error: More than one method with same name and argument list
cannot be defined in a same class.

Question 2 – return type is different. Method name & argument list same.

class Demo2
{
public double myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample5
{
public static void main(String args[])
{
Demo2 obj2= new Demo2();
obj2.myMethod(10,10);
obj2.myMethod(20,12);
}
}
Answer:
It will throw a compilation error: More than one method with same name and argument list
cannot be given in a class even though their return type is different. Method return type
doesn’t matter in case of overloading.

Method overriding in java with example

Declaring a method in subclass which is already present in parent class is known as method
overriding. Earlier we shared method overloading in java. In this tutorial we will see method
overriding with examples.

Example:

One of the simplest example – Here Boy class extends Human class. Both the classes have a
common method void eat(). Boy class is giving its own implementation to the eat() method or in
other words it is overriding the method eat().
Muka Surat / Page : 20
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

class Human{
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
obj.eat();
}
}
Output:

Boy is eating

Advantage of method overriding

The main advantage of method overriding is that the class can give its own specific
implementation to an inherited method without even modifying the parent class (base class).

Method Overriding in dynamic method dispatch

Dynamic method dispatch is a technique which enables us to assign the base class reference
to a child class object. As you can see in the below example that the base class reference is
assigned to child class object.

class ABC{
public void disp()
{
System.out.println("disp() method of parent class");
}
public void abc()
{
System.out.println("abc() method of parent class");
}
}
class Test extends ABC{
public void disp(){
System.out.println("disp() method of Child class");
}
public void xyz(){
System.out.println("xyz() method of Child class");
}
Muka Surat / Page : 21
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

public static void main( String args[]) {


//Parent class reference to child class object
ABC obj = new Test();
obj.disp();
obj.abc();
}
}
Output:

disp() method of Child class


abc() method of parent class

Note: In dynamic method dispatch the object can call the overriding methods of child class and
all the non-overridden methods of base class but it cannot call the methods which are newly
declared in the child class. In the above example the object obj was able to call
thedisp()(overriding method) and abc()(non-overridden method of base class). However if you
try to call the xyz() method (which has been newly declared in Test class) [obj.xyz()] then it
would give compilation error with the following message:

Exception in thread "main" java.lang.Error: Unresolved compilation


problem: The method xyz() is undefined for the type ABC

Rules of method overriding in Java

1. Argument list: The argument list of overriding method must be same as that of the
method in parent class. The data types of the arguments and their sequence should be
maintained as it is in the overriding method.
2. Access Modifier: The Access Modifier of the overriding method (method of subclass)
cannot be more restrictive than the overridden method of parent class. For e.g. if the
Access Modifier of base class method is public then the overriding method (child class
method ) cannot have private, protected and default Access modifier as all of the three
are more restrictive than public.
Muka Surat / Page : 22
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23
For e.g. This is not allowed as child class disp method is more restrictive(protected) than
base class(public)

class MyBaseClass{
public void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends MyBaseClass{
protected void disp(){
System.out.println("Child class method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}
}
Output:

Exception in thread "main" java.lang.Error: Unresolved compilation


problem: Cannot reduce the visibility of the inherited method from MyBaseClass
However this is perfectly valid scenario as public is less restrictive than protected. Same
access modifier is also a valid one.

class MyBaseClass{
protected void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends MyBaseClass{
public void disp(){
System.out.println("Child class method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}
}
Output:

Child class method

3. private, static and final methods cannot be overridden as they are local to the class.
However static methods can be re-declared in the sub class, in this case the sub-class
method would act differently and will have nothing to do with the same static method of
parent class.
Muka Surat / Page : 23
NO. KOD / CODE NO. DKB4333 / KP(3/3)
Drpd / of : 23

4. Overriding method (method of child class) can throw anyunchecked exceptions,


regardless of whether the overridden method(method of parent class) throws any
exception or not. However the overriding method should not throw checked
exceptions that are new or broader than the ones declared by the overridden method. We
will discuss this in detail with example in the upcoming tutorial.
5. Binding of overridden methods happen at runtime which is known as dynamic binding.
6. If a class is extending an abstract class or implementing aninterface then it has to
override all the abstract methods unless the class itself is a abstract class.

Super keyword in Overriding

super keyword is used for calling the parent class


method/constructor. super.methodname() calling the specified method of base class
while super() calls the constructor of base class. Let’s see the use of super in Overriding.

class ABC{
public void mymethod()
{
System.out.println("Class ABC: mymethod()");
}
}
class Test extends ABC{
public void mymethod(){
//This will call the mymethod() of parent class
super.mymethod();
System.out.println("Class Test: mymethod()");
}
public static void main( String args[]) {
Test obj = new Test();
obj.mymethod();
}
}
Output:

Class ABC: mymethod()


Class Test: mymethod()

Anda mungkin juga menyukai