CSG2H3 Object Oriented Programming
Polymorphism
-RSM-
Apa itu Polimorfisme?
Apa itu Polimorfisme? The ability of objects belonging to different types to respond to method calls of the same name, each one according to an appropriate type-specific behavior [Wikipedia]. The ability of a variable entity or data structure element, at run time, to become attached to objects of different types [Meyer]. A concept where a single name may denote objects of different classes that are related by some common base class [Booch].
Apa itu Polimorfisme? Kemampuan suatu objek untuk digunakan di banyak tujuan berbeda dengan nama yang sama. Kemampuan objek dalam memberikan respon yang berbeda terhadap message yang mempunyai nama yang sama.
Kemampuan untuk mempunyai beberapa bentuk yang berbeda. Disebut juga: – dynamic binding – late binding – run-time binding
Gambaran Polimorfisme // Program Utama class TesPoligon { Poligon p = new Poligon(); ...
Poligon
SegiEmpat
SegiTiga
SegiEmpat s = new SegiEmpat(); SegiTiga t = new SegiTiga(); Lingkaran l = new Lingkaran();
Lingkaran
variabel p menunjuk objek yang diciptakan dari kelas Poligon
}
p = s; // ok krn instan kelas anak juga instan kelas induk ... variabel s menunjuk
variabel p diubah sehingga menunjuk objek dari kelas SegiEmpat
objek yang diciptakan dari kelas SegiEmpat
Gambaran Polimorfisme [2] Sebelum:
Sesudah:
Poligon p = new Poligon();
p = s;
p
Poligon
p
Poligon
s
SegiEmpat
SegiEmpat s = new SegiEmpat(); s
SegiEmpat
Gambaran Polimorfisme [3] class SegiEmpat { . . . public String display() { return ("Segi Empat" + "\no Panjang : " + getPanjang() + "\no Lebar : " + getLebar() + "\no Luas : " + Luas() + "\no Keliling : " + Keliling()); } }
class Lingkaran { . . . public String display() { return (“Lingkaran" + "\no jari-jari: " + getRadius() + "\no Luas : " + Luas() + "\no Keliling : " + Keliling()); } }
class TesPoligon { public static void main(String args[]) { // Deklarasi array Poligon[] p = new Poligon[3]; // Add p[0] = p[1] = p[2] =
array poligon new SegiEmpat(17, 8); new Segitiga(21,4) new Lingkaran(10);
// Display informasi for (int i=0; i
Gambaran Polimorfisme [4]
Hasil eksekusi method displayInfo() yang dipunyai masing-masing objek
Bentuk-bentuk Polimorfisme Overloading – Method – Constructor
Overriding
Pendefinisian ulang method yang diturunkan kelas induk oleh kelas anak. Coercion & Casting Sub-type Polymorphism
Method Overloading Menuliskan kembali method dengan nama yang sama pada suatu class. Tujuan : memudahkan penggunaan/ pemanggilan method dengan fungsionalitas yang mirip.
Aturan Pendeklarasian Method Overloading Nama method harus sama
Daftar parameter harus berbeda Return type boleh sama, juga boleh berbeda
Daftar Parameter pada Method Overloading Perbedaan daftar parameter bukan hanya terjadi pada perbedaan banyaknya parameter, tetapi juga urutan dari parameter tersebut. Misalnya saja dua buah parameter berikut ini : – function_member(int x, String n) – function_member(String n, int x) Dua parameter tersebut juga dianggap berbeda daftar parameternya.
Daftar Parameter pada Method Overloading Daftar parameter tidak terkait dengan penamaan variabel yang ada dalam parameter. Misalnya saja 2 daftar parameter berikut : – function_member(int x) – function_member(int y)
Dua daftar parameter diatas dianggap sama karena yang berbeda hanya penamaan variabel parameternya saja.
Contoh Method Overloading
Contoh Method Overloading public class Bentuk { … public void Gambar(int … } public void Gambar(int … } public void Gambar(int … } public void Gambar(int … } }
t1) {
t1, int t2) {
t1, int t2, int t3) {
t1, int t2, int t3, int t4) {
Contoh Method Overloading
Method Overloading antara Parent Class & Sub Class Overloading juga bisa terjadi antara parent class dengan subclass-nya jika memenuhi ketiga syarat overload. Misalnya saja dari class Bentuk pada contoh sebelumnya kita turunkan sebuah class baru yang bernama WarnaiBentuk.
Method Overloading antara Parent Class & Sub Class public class WarnaiBentuk extends Bentuk { public void Gambar(String warna, int t1, int t2, int3) {
… } public void Gambar(String warna, int t1, int t2, int3, int t4){
… } … }
Constructor Overloading
Contoh Constructor Overloading
Memanggil Parent Class Constructor
Overriding Subclass yang berusaha memodifikasi tingkah laku yang diwarisi dari superclass. Tujuan: subclass memiliki tingkah laku yang lebih spesifik.
Dilakukan dengan cara mendeklarasikan kembali method milik parent class di subclass.
Overriding Deklarasi method pada subclass harus sama dengan yang terdapat di super class. Kesamaan pada: – Nama – Return type – Daftar parameter (jumlah, tipe, dan urutan)
Method pada parent class disebut overriden method Method pada subclass disebut overriding method.
Contoh Overriding public class Employee {
public class Manager extends Employee{
protected String name;
protected String department;
protected double Salary; protected Date birthday;
public String getDetails(){ return “Name: “+name+”\n”+”Salary: “+salary; } }
public String getDetails(){ return “Name: “+name+”\n”+”Salary: “+salary+”\n”+”Manager of: “+department; } }
Contoh Overriding public class Animal { public void SetVoice() { System.out.println(“Blesepblesep”); } } public class Dog extends Animal { public void SetVoice() { System.out.println(“Hug hug”); } }
Aturan Overriding Mode akses overriding method harus sama atau lebih luas dari pada overriden method. Subclass hanya boleh meng-override method superclass satu kali saja, tidak boleh ada lebih dari satu method pada kelas yang sama yang sama persis.
Casting taking an Object of one particular type and “turning it into” another Object type Type Casting Object Casting
Type Casting Assigning a value of one type to a variable of another type
Widening Casting – Smaller type to larger type – Implicit – Automatic type conversion – The two types must compatible – The target type is larger than the source type
Narrowing Casting – Larger type to smaller type – Explicit
Widening Casting/ Type Coercion Implicit type conversion, supplied automatically by programming language even if the programmer leaves it out Explicit type conversion in Java: double x; x = (double) 2;
Coercion in Java double x; x = 2;
Contoh Parameter Coercion/ Widening Casting void f(double x) { … }
f((byte) 1); f((short) 2); f('a'); f(3); f(4L); f(5.6F);
This f can be called with any type of parameter. Java is willing to coerce to type double
Contoh Parameter Coercion/ Widening Casting public class Driver{ public static void main(String args[]){ int i = 50; long l = i; float f = l; System.out.println(“int value: “ + i); System.out.println(“long value: “ + l); System.out.println(“float value: “ + f); } }
> int value: 50 > long value: 50 > float value: 50.0
Narrowing Casting public class Driver{ public static void main(String args[]){ double d = 25.16; long l = (long)d; int i = (int)l; System.out.println(“double value: “ + d); System.out.println(“long value: “ + l); System.out.println(“int value: “ + i); } }
> double value: 25.16 > long value: 25 > int value: 25
Object Casting Turn an object of a class to another class Both classes should have inheritance or implement relationship Upcasting – Implicit – Assign subclass object to a super class object
Downcasting – Explisit – Assign a super class object to a subclass object
Virtual Method Invocation
Virtual Method Invocation Virtual method invocation is the form of Upcasting At the time of the object that has been created calling overridden method in the parent class, the Java compiler will do the invocation (call) to the overriding method in a subclass, which is supposed to be called is overridden
Example public class Parent{
public class ChildA extends Parent{
public String toString(){ return “this is class Parent”; }
public String toString(){ return “this is class Child A”; }
}
}
public class ChildB extends Parent{
public class GrandChildA extends ChildA{
public String toString(){ return “this is class Child B”; } }
public String toString(){ return “this is class Grand Child”; } }
Example public class Driver{ public static void main(String args[]){ Parent p = new Parent(); ChildA cA = new ChildA(); ChildB cB = new ChildB(); GrandChildA gC = new GrandChildA(); System.out.println(p.toString()); System.out.println(cA.toString()); System.out.println(cB.toString()); System.out.println(gC.toString()); } }
> > > >
this this this this
is is is is
method method method method
Parent Child A Child B Grand Child
Example Upcasting/VMI public class Driver{ public static void main(String args[]){ Parent castP; castP = new Parent(); System.out.println(castP.toString()); castP = new ChildA(); System.out.println(castP.toString()); castP = new ChildB(); System.out.println(castP.toString()); castP = new GrandChildA(); System.out.println(castP.toString()); } }
> > > >
this this this this
is is is is
method method method method
Parent Child A Child B Grand Child
Example Upcasting/VMI public class Driver{ public static void main(String args[]){ Parent castP; GrandChildA gC = new GrandChildA(); ChildB cB = new ChildB(); castP = gC; System.out.println(castP.toString()); castP = cB; System.out.println(castP.toString()); } }
> this is method Grand Child > this is method Child B
Upcasting castP = new ChildA();
Object castP has a behavior that is in accordance with the runtime type, not the compile type When compile-time castP is a Parent When runtime castP is ChildA Therefore – castP can only access variable Parent – castP can only access method ChildA
Example public class Parent{ protected int number = 10;
public class ChildA extends Parent{ protected int number = 20;
public String toString(){ return “Parent ” + number; }
public String toString(){ return “Child A ” + number; } public String methodA(){ return “method Child A”; }
}
}
public class ChildB extends Parent{ protected int number = 30;
public class GrandChildA extends ChildA{ protected int number = 40;
public String toString(){ return “Child B ” + number; } public String methodB(){ return “method Child B”; } }
public String toString(){ return “Grand Child ” + number; } public String methodGrand(){ return “method Grand Child A”; } }
Example public class Driver{ public static void main(String args[]){ Parent p = new Parent(); ChildA cA = new ChildA(); ChildB cB = new ChildB(); GrandChildA gC = new GrandChildA(); System.out.println(p.toString()); System.out.println(cA.toString()); System.out.println(cB.toString()); System.out.println(gC.toString()); } }
> > > >
Parent 10 Child A 20 Child B 30 Grand Child 40
Example public class Driver{ public static void main(String args[]){ Parent p = new Parent(); ChildA cA = new ChildA(); ChildB cB = new ChildB(); GrandChildA gC = new GrandChildA(); Parent castP;
castP = cA; System.out.println(castP.toString()); System.out.println(castP.number); castP = gC; System.out.println(castP.toString()); System.out.println(castP.number); } }
> > > >
Child A 20 10 Grand Child 40 10
Example public class Driver{ public static void main(String args[]){ Parent p = new Parent(); ChildA cA = new ChildA(); ChildB cB = new ChildB(); GrandChildA gC = new GrandChildA(); Parent castP;
> method Child A
System.out.println(cA.methodA()); castP = cA; System.out.println(castP.methodA()); } }
//compile error: cannot find symbol
DownCasting Return the upcasted object back to its original class object Explicit casting
Example public class Driver{ public static void main(String args[]){ Parent castP; castP = new GrandChildA(); System.out.println(castP.toString()); System.out.println(castP.methodA());
> Grand Child 40 > Method Child A > Method Grand Child A
GrandChildA castG; //castG = castP; castG = (GrandChildA) castP; System.out.println(castG.toString()); System.out.println(castG.methodA()); System.out.println(castG.methodGrand());
> Grand Child 40 > Method Child A
ChildA castA = (ChildA) castP; System.out.println(castA.toString()); System.out.println(castA.methodA()); }
}
> Grand Child 40 > Compile error
Example public class Driver{ public static void main(String args[]){ Parent castP; castP = new GrandChildA(); System.out.println(castP.toString()); System.out.println( ((ChildA)castP).methodA() ); System.out.println( ((GrandChildA)castP).methodGrand() ); } }
> Grand Child 40 > Method Child A > Method Grand Child A
Example public class Driver{ public static void main(String args[]){ Parent castP; ChildA castA; GrandChildA gC;
> Child B 30 > ClassCastException
castP = new ChildB(); System.out.println(castP.toString()); castA = (ChildA)castP; System.out.println(castA.toString()); System.out.println(castA.methodA()); }
}
//runtime error: Class Cast Exception Downcast only to it’s original object
Example public class Driver{ public static void main(String args[]){ Parent castP; ChildA castA; GrandChildA gC;
> Child A 20 > ClassCastException
castP = new ChildA(); System.out.println(castP.toString()); gC = (GrandChildA)castP; System.out.println(gC.toString()); System.out.println(gC.methodA()); System.out.println(gC.methodGrand()); }
}
//runtime error: Class Cast Exception Downcast only to it’s original object
Downcasting Before doing downcasting, upcasting must be done Can only downcast to original class or its parents’ class
To check whether the object can be casted – Use instanceof keyword
Keyword instanceof Used to test if an object is of a specified type – test if an object is an instance of a class, – an instance of a subclass, – or an instance of a class that implements a particular interface
(Object instanceof Class) boolean
Example System.out.println("p instanceof Parent: " + (p instanceof Parent)); System.out.println("p instanceof ChildA: " + (p instanceof ChildA)); System.out.println("cA instanceof Parent: " + (cA instanceof Parent)); System.out.println("cA instanceof ChildA: " + (cA instanceof ChildA)); System.out.println("cB instanceof ChildA: " + (cB instanceof ChildA)); System.out.println(“cB instanceof Parent : " + (cB instanceof Parent)); System.out.println("cG instanceof ChildA: " + (cG instanceof ChildA)); System.out.println("cG instanceof Parent: " + (cG instanceof Parent));
> p instanceof Parent: true > p instanceof ChildA: false > cA instanceof Parent: true > cA instanceof ChildA: true > //compile error, cannot be converted > cB instanceof Parent : true
> cG instanceof ChildA: true > cG instanceof Parent : true
Example public class Driver{ public static void main(String args[]){ Parent castP; ChildA castA; GrandChildA gC; castP = new ChildA(); System.out.println(castP.toString()); if(castP instanceof GrandChildA) { gC = (GrandChildA)castP; System.out.println(gC.toString()); System.out.println(gC.methodA()); System.out.println(gC.methodGrand()); } } }
> Child A 40 >
Benefits and Downsides Flexibility – Model Object
Heterogeneous Collection Polymorphic Arguments Run-time exception – ClassCastException
Heterogeneous Collection Collections of objects with different class types public class Driver{ public static void main(String args[]){ Parent listP[] = new Parent[4]; listP[0] = new ChildB(); listP[1] = new ChildA(); listP[2] = new Parent(); listP[3] = new GrandChildA(); } }
Example for(int i = 0; i < 4; i++){
> 0 Child B 30 > method Child B
System.out.println(i+" "+listP[i].toString()); if(listP[i] instanceof ChildA) { ChildA cA = (ChildA)listP[i]; System.out.println(cA.methodA()); } if(listP[i] instanceof ChildB) { ChildB cB = (ChildB)listP[i]; System.out.println(cB.methodB()); } if(listP[i] instanceof GrandChildA) { GrandChildA gC = (GrandChildA)listP[i]; System.out.println(gC.methodGrand()); } }
> 1 Child A 20 > method Child A > 2 Parent 10 > 3 Grand Child 40 > method Child A > method Grand Child A
Polymorphic Arguments/ Subtype Polymorphism Polymorphic arguments adalah tipe data suatu argumen pada suatu method yang bisa menerima suatu nilai yang bertipe subclass-nya.
Polymorphic Arguments/ Subtype Polymorphism
Polymorphic Arguments/ Subtype Polymorphism class Pegawai { … } class Manajer extends Pegawai { … } public class Tes { public static void Proses(Pegawai peg) { … } public static void main(String args[]) { Manajer man = new Manajer(); Proses(man); } }
Exercise
Shapes
Exercise - Detail
-
int numSides String color
+ Shapes () + Shapes (int numSides, String color) + int getNumSides() + String getColor() + double getArea() + double getPerimeter() + String getDetail()
<
> Resizable
+ resize (double zoom)
Rectangle -
double height double width
+ Rectangle (double height, double width) + Rectangle (int numSides, String color, double height, double width) + double getArea() + double getPerimeter() + String getDetail()
Triangle -
double base double height
+ Triangle(int base, int height) + Triangle (int numSides, String color, double base, double height) + double getEdgeLength() + double getArea() + double getPerimeter() + String getDetail()
Exercise - Detail Buat implementasi class diagram tersebut dalam bahasa Java! (Asumsi: segitiga yang dimaksud pada kelas Triangle adalah segitiga sama kaki) Buat driver dengan skenario: – Instansiasi object dari class Rectangle dan Triangle. – Masukkan object-object di atas ke ArrayList dari Shape. – Lakukan iterasi Shape dalam ArrayList. Jika Shape bisa diresizable, maka lakukan resize 0,5 kali. Kemudian tampilkan perimeter dan area untuk setiap Shape yang ada di ArrayList.
Exercise – Contoh Running Program
THANK YOU