sisteminformasifilkom ub semester …€¢ketika kita mencoba memanggil method getname dari...

26
PEMROGRAMAN LANJUT Fakultas Ilmu Komputer, Universitas Brawijaya POLIMORPHISM Dr. Eng. Herman Tolle Sistem Informasi FILKOM UB Semester Genap 2016/2017

Upload: lamnhan

Post on 10-Apr-2019

224 views

Category:

Documents


0 download

TRANSCRIPT

PEMROGRAMAN LANJUT

Fakultas Ilmu Komputer, Universitas Brawijaya

POLIMORPHISM

Dr.Eng.HermanTolle

Sistem Informasi FILKOM UBSemester Genap 2016/2017

Kata Kunci

• Polymorphism | Polimorfisme• Supertype, Subtype• Static Polymorphism | Static Binding• Dynamic Polymorphism• Dynamic Binding• Casting

Polymorphism

• Polymorphism | Polimorfisme• Morph à berubah bentuk

• Kemampuan dari sebuah objek untuk berubah bentuk menyesuaikan dengan referensi objek yang ditentukan oleh program yang kita buat

• Static Polymorphism dan Dynamic Polymorphism

4

PolymorphismPolymorphism 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 supertype for Circle.

5

Polymorphism

Polymorphism: sebuah variabel dari sebuah supertypedapat merefer ke sebuah objek subtype

Sebuah kelas dapat dianggap sebagai sebuah tipe data

Sebuah type yang didefinisikan oleh subclass disebutsubtype, dan tipe yang didefiniskan oleh kelasinduknya disebut supertype.

Circle is a subtype of GeometricObject and GeometricObject is a supertype for Circle.

6

Polymorphism, Dynamic Binding and Generic Programmingpublic 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 capability is known as dynamic binding.

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 binding.

Demo Overloadclass 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;

} }

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 } }

Results?

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-overridedari superclass td, yang akan dipanggil (dikerjakan) adalah versi metode dari subclass-nya

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!!”); }

}

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!!

} }

Contohpublic 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();

}}

• 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 method overriding

Contoh

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

• Dalam Java, kita dapat membuat referensi yang merupakan tipe darisuperclass 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}

• Sekarang dimisalkan kita punya method getName dalam superclassPerson 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;

}

public static void main(String[] args){

Person ref;Student studentObject = new Student();Employee employeeObject = new Employee();ref = studentObject; //Person menunjuk kepada object StudentString temp = ref.getName(); //getName dari Student class dipanggilSystem.out.println( temp );

ref = employeeObject; //Person menunjuk kepada object EmployeeString temp = ref.getName(); //getName dari Employee class dipanggilSystem.out.println( temp );

}

• KetikakitamencobamemanggilmethodgetNamedarireferencePersonref,methodgetName dariobjectStudentakandipanggil.

• Sekarang,jikakitaberikanrefkeobjectEmployee,methodgetName dariEmployeeakandipanggil.

• Kemampuandarireference untukmengubahsifatmenurutobjectapayangdijadikanacuandinamakanpolimorfisme.

• Polimorfismemenyediakanmultiobject darisubclassesyangberbedauntukdiperlakukansebagaiobjectdarisuperclasstunggal,secaraotomatismenunjukmethodyangtepatuntukmenggunakannyakeparticularobjectberdasarsubclassyangtermasukdidalamnya

•Contohlainyangmenunjukkanpropertipolimorfismeadalahketikakitamencobamelaluireference kemethod.

•MisalkankitapunyamethodstaticprintInformation yangmengakibatkanobjectPersonsebagaireference,kitadapatme-referencedaritipeEmployeedantipeStudentkemethodiniselamaitumasihsubclassdariclassPerson.

public static main( String[] args ){

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

}

public static printInformation( Person p ){. . . .

}

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

Generic Programmingpublic 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 dynamically.

22

Casting ObjectsYou 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 castingm(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

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:

Student b = (Student)o; // Explicit casting

24

Casting fromSuperclass 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

The instanceof OperatorUse 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());

...}

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