• Tidak ada hasil yang ditemukan

POLIMORPHISM PEMROGRAMAN LANJUT. Dr. Eng. Herman Tolle. Sistem Informasi FILKOM UB Semester Genap 2016/2017

N/A
N/A
Protected

Academic year: 2021

Membagikan "POLIMORPHISM PEMROGRAMAN LANJUT. Dr. Eng. Herman Tolle. Sistem Informasi FILKOM UB Semester Genap 2016/2017"

Copied!
26
0
0

Teks penuh

(1)

PEMROGRAMAN LANJUT

Fakultas Ilmu Komputer, Universitas Brawijaya

POLIMORPHISM

Dr. Eng. Herman Tolle

Sistem Informasi FILKOM UB Semester Genap 2016/2017

(2)

Kata Kunci

• Polymorphism | Polimorfisme

• Supertype, Subtype

• Static Polymorphism | Static Binding

• Dynamic Polymorphism

• Dynamic Binding

• Casting

(3)

Polymorphism

• Polymorphism | Polimorfisme

• Morph à berubah bentuk

• Kemampuan dari sebuah objek untuk berubah bentuk

menyesuaikan dengan referensi objek yang ditentukan oleh program yang kita buat

(4)

4

Polymorphism

Polymorphism means that a variable of a

supertype can refer to a subtype object.

A class defines a type. A type defined by a

subclass is called a subtype, and a type defined by

its superclass is called a supertype.

Therefore, you can say that Circle is a subtype of

GeometricObject and GeometricObject is a

(5)

5

Polymorphism

Polymorphism: sebuah variabel dari sebuah

supertype

dapat merefer ke sebuah objek subtype

Sebuah kelas dapat dianggap sebagai sebuah tipe data

Sebuah

type

yang didefinisikan oleh subclass disebut

subtype, dan tipe yang didefiniskan oleh kelas

induknya disebut supertype.

Circle is a subtype of GeometricObject and

GeometricObject is a supertype for Circle.

(6)

6

Polymorphism, Dynamic Binding and Generic Programming

public class PolymorphismDemo {

public static void main(String[] args) { m(new GraduateStudent());

m(new Student()); m(new Person()); m(new Object()); }

public static void m(Object x) { System.out.println(x.toString()); }

}

class GraduateStudent extends Student { }

class Student extends Person { public String toString() {

return "Student"; }

}

class Person extends Object { public String toString() {

return "Person"; }

}

Method m takes a parameter of the Object type. You can invoke it with any object.

An object of a subtype can be used wherever its supertype value is required. This feature is

known as polymorphism.

When the method m(Object x) is executed, the argument x’s toString method is invoked. x may be an instance of GraduateStudent, Student, Person, or Object. Classes

GraduateStudent, Student, Person, and

Object have their own implementation of the toString method. Which implementation is used will be determined dynamically by the Java Virtual Machine at runtime. This

(7)

7

Static Polymorphism

• In Java, static polymorphism is achieved through method overloading.

• Method overloading means there are several methods present in a class having the same name but different types/order/number of parameters.

• At compile time, Java knows which method to invoke by checking the method signatures.

• This is called compile time polymorphism or static

(8)

Demo Overload

class DemoOverload{

public int add(int x, int y) { //method 1 return x+y;

}

public int add(int x, int y, int z){ //method 2 return x+y+z;

}

public int add(double x, int y){ //method 3 return (int)x+y;

}

public int add(int x, double y){ //method 4 return x+(int)y;

} }

(9)

class Test {

public static void main(String[] args){ DemoOverload demo=new DemoOverload();

System.out.println(demo.add(2,3)); //method 1 called System.out.println(demo.add(2,3,4)); //method 2 called System.out.println(demo.add(2,3.4)); //method 4 called System.out.println(demo.add(2.5,3)); //method 3 called } }

(10)

Dynamic Polymorphism:

• Misalkan suatu subclass meng-override suatu

metode dari superclass nya

• Anggap jika dalam program kita membuat suatu

objek dari subclass dan meng-assign-kan ke

referensi superclass

• Maka jika kita memanggil metode yg di-override

dari superclass td, yang akan dipanggil (dikerjakan)

adalah versi metode dari subclass-nya

(11)

class Vehicle{

public void move(){

System.out.println(“Vehicles can move!!”); } }

class MotorBike extends Vehicle{ public void move(){

System.out.println(“MotorBike can move and accelerate too!!”); }

(12)

class Test{

public static void main(String[] args){

Vehicle vh=new MotorBike();

vh.move(); // prints MotorBike can move and accelerate too!!

vh=new Vehicle();

vh.move(); // prints Vehicles can move!!

} }

(13)

Contoh

public class Bicycle {}

public class RoadBike extends Bicycle {}

public class MountainBike extends Bicycle {}

public class TestBikes {

public static void main(String[] args){

Bicycle bike01, bike02, bike03;

bike01 = new Bicycle(20, 10, 1);

bike02 = new MountainBike(20, 10, 5, "Dual");

bike03 = new RoadBike(40, 20, 8, 23); bike01.printDescription();

bike02.printDescription(); bike03.printDescription(); }

(14)

• An object in Java that passes more than one

IS-A tests is polymorphic in nature

• Sebuah objek yang dapat diisi oleh lebih dari

satu bentuk IS-A

ß

Polimorfism

• Static polymorphism in Java is achieved by

method overloading

• Dynamic polymorphism in Java is achieved by

(15)

Contoh

• Class induk Person dan subclass Student, kita tambahkan subclass lain dari Person yaitu Employee.

• Dalam Java, kita dapat membuat referensi yang merupakan tipe dari superclass ke sebuah object dari subclass tersebut. Sebagai contohnya,

public static void main(String[] args)

{

Person ref;

Student studentObject = new Student(); Employee employeeObject = new Employee();

ref = studentObject; //Person menunjuk kepada object Student //beberapa kode di sini

(16)

• Sekarang dimisalkan kita punya method getName dalam superclass Person kita, dan kita override method ini dalam kedua subclasses Student dan Employee,

public class Person

{

public String getName(){

System.out.println(“Person Name:” + name); return name;

} }

public class Student extends Person

{

public String getName(){

System.out.println(“Student Name:” + name); return name;

} }

public class Employee extends Person

{

public String getName(){

System.out.println(“Employee Name:” + name); return name;

(17)

public static void main(String[] args) {

Person ref;

Student studentObject = new Student(); Employee employeeObject = new Employee();

ref = studentObject; //Person menunjuk kepada object Student

String temp = ref.getName(); //getName dari Student class dipanggil

System.out.println( temp );

ref = employeeObject; //Person menunjuk kepada object Employee

String temp = ref.getName(); //getName dari Employee class dipanggil

System.out.println( temp );

(18)

• Ketika kita mencoba memanggil method getName dari reference Person ref, method getName dari object Student akan dipanggil. • Sekarang, jika kita berikan ref ke object Employee, method getName dari Employee akan dipanggil. • Kemampuan dari reference untuk mengubah sifat menurut object apa yang dijadikan acuan dinamakan polimorfisme. • Polimorfisme menyediakan multiobject dari subclasses yang berbeda untuk diperlakukan sebagai object dari superclass tunggal, secara otomatis menunjuk method yang tepat untuk menggunakannya ke particular object berdasar subclass yang termasuk di dalamnya

(19)

• Contoh lain yang menunjukkan properti polimorfisme adalah ketika kita mencoba melalui reference ke method. • Misalkan kita punya method static printInformation yang mengakibatkan object Person sebagai reference, kita dapat me-reference dari tipe Employee dan tipe Student ke method ini selama itu masih subclass dari class Person.

public static main( String[] args ) {

Student studentObject = new Student(); Employee employeeObject = new Employee();

printInformation( studentObject ); printInformation( employeeObject );

}

public static printInformation( Person p ) {

. . . . }

(20)

20

Method Matching vs. Binding

• Matching a method signature and binding a

method implementation are two issues.

• The compiler finds a matching method

according to parameter type, number of

parameters, and order of the parameters at

compilation time.

• A method may be implemented in several

subclasses.

• The Java Virtual Machine dynamically binds the

implementation of the method at runtime.

(21)

21

Generic Programming

public class PolymorphismDemo {

public static void main(String[] args) { m(new GraduateStudent());

m(new Student()); m(new Person()); m(new Object()); }

public static void m(Object x) { System.out.println(x.toString()); }

}

class GraduateStudent extends Student { }

class Student extends Person { public String toString() {

return "Student"; }

}

class Person extends Object { public String toString() {

return "Person"; }

}

Polymorphism allows methods to be used generically for a wide

range of object arguments. This is known as generic programming. If a method’s parameter type is a superclass (e.g., Object), you may pass an object to this method of any of the parameter’s subclasses (e.g., Student or String). When an object (e.g., a Student object or a String object) is used in the

method, the particular

implementation of the method of the object that is invoked (e.g., toString) is determined

(22)

22

Casting Objects

You have already used the casting operator to convert variables of one primitive type to another. Casting can also be used to

convert an object of one class type to another within an

inheritance hierarchy. In the preceding section, the statement

m(new Student());

assigns the object new Student() to a parameter of the Object type. This statement is equivalent to:

Object o = new Student(); // Implicit casting

m(o);

The statement Object o = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object.

(23)

23

Why Casting Is Necessary?

Suppose you want to assign the object reference o to a variable of the Student type using the following statement:

Student b = o;

A compile error would occur. Why does the statement Object o =

new Student() work and the statement Student b = o doesn’t?

This is because a Student object is always an instance of Object, but an Object is not necessarily an instance of Student. Even

though you can see that o is really a Student object, the compiler is not so clever to know it. To tell the compiler that o is a Student object, use an explicit casting. The syntax is similar to the one used for casting among primitive data types. Enclose the target object type in parentheses and place it before the object to be cast, as follows:

(24)

24

Casting from

Superclass to Subclass

Explicit casting must be used when casting an

object from a superclass to a subclass. This type

of casting may not always succeed.

Apple x = (Apple)fruit; Orange x = (Orange)fruit;

(25)

25

The

instanceof

Operator

Use the instanceof operator to test whether an object is an instance of a class:

Object myObject = new Circle(); ... // Some lines of code

/** Perform casting if myObject is an instance of Circle */

if (myObject instanceof Circle) {

System.out.println("The circle diameter is " + ((Circle)myObject).getDiameter());

... }

(26)

Summary

• Static Polymorphism à Method overloading • Dynamic Polymorphism à Method overriding

• Sebuah objek (dengan tipe data) dari class induk, dapat diisi dengan objek dari class turunannya ß Polymorphism

• Polimorfism adalah kemampuan dari Bahasa pemrograman untuk memproses objek secara berbeda tergantung pada tipe data atau class nya

• More specifically, it is the ability to redefine methods for derived classes. Kemampuan untuk mendefiniskan ulang metode berdasarkan kelas turunannya

Referensi

Dokumen terkait

program Sistem Pakar cara penanaman tebu menggunakan metode forward chaining ini dapat membantu para petani bagaimana menanam tebu yang baik.. Bagaimana membuat sistem

1) Sadar akan hak dan kewajibannya serta tanggung jawabnya sebagai warga Negara terhadap kepentingan bangsa dan Negara. 2) Sadar dan taat pada hukum dan semua

Dengan ini saya menyatakan dengan sesungguhnya bahwa dalam skripsi ini tidak terdapat keseluruhan atau sebagian tulisan orang lain yang saya ambil dengan cara menyalin,

Penelitian ini bermaksud mengevaluasi pelaksanaan Sistem Manajemen Mutu ISO 9001:2008 pada SMK Negeri 2 Salatiga, berdasarkan 8 (delapan) prinsip standar sistem manajemen

Pada dasarnya likuiditas dan profitabilitas saling bertolak belakang, likuiditas dari hasil penelitian ini mampu memberikan peningkatan terhadap tingkat

KARUNIA JAYA / TUTUT ERNA

KARUNIA JAYA / TUTUT ERNA WAHYUNI, S.Si.. KARUNIA JAYA / TUTUT ERNA

Dengan adanya permainan pengenalan mata uang rupiah berbasis Android ini diharapkan untuk memberikan pengenalan tentang mata uang rupiah dan dapat melatih kemampuan