0 6 R E V IS E D 8 FE B 2 0 1 3
CSG2H3
Object Oriented Programming
E D 8 FE B 2 0 1 3
0 6 R E V IS E D 8 FE B 2 0 1 3
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].
E D 8 FE B 2 0 1 3
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
0 6 R E V IS E D 8 FE B 2 0 1 3
// Program Utama
class TesPoligon {
Poligon p = new Poligon();
...
SegiEmpat s = new SegiEmpat();
SegiTiga t = new SegiTiga();
Lingkaran l = new Lingkaran();
p = s;
// ok krn instan kelas
anak juga instan kelas induk
...
}
Gambaran Polimorfisme
PoligonSegiEmpat SegiTiga Lingkaran
variabel p menunjuk
objek yang diciptakan
dari kelas Poligon variabel s menunjuk
objek yang diciptakan dari kelas SegiEmpat
E D 8 FE B 2 0 1 3
Gambaran Polimorfisme
[2]
Poligon SegiEmpat p sPoligon p = new Poligon();
SegiEmpat s = new SegiEmpat();
Sebelum:
Poligon SegiEmpat p sp = s;
Sesudah:
0 6 R E V IS E D 8 FE B 2 0 1 3 class SegiEmpat { . . .
public String display() { return ("Segi Empat"
+ "\no Panjang : " + getPanjang() + "\no Lebar : " + getLebar() + "\no Luas : " + Luas()
+ "\no Keliling : " + Keliling()); }
}
Gambaran Polimorfisme [3]
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 array poligon
p[0] = new SegiEmpat(17, 8); p[1] = new Segitiga(21,4) p[2] = new Lingkaran(10); // Display informasi
for (int i=0; i<p.length; i++) {
System.out.println(p[i].display()); }
} }
Method display () yang dieksekusi ditentukan berdasarkan rujukan ke
E D 8 FE B 2 0 1 3
Gambaran Polimorfisme [4]
Hasil eksekusi method
displayInfo()
yang dipunyai
masing-masing objek
0 6 R E V IS E D 8 FE B 2 0 1 3
Overloading
–
Method
–
Constructor
Overriding
Pendefinisian ulang method yang diturunkan kelas
induk oleh kelas anak.
Coercion & Casting
Sub-type Polymorphism
E D 8 FE B 2 0 1 3
Menuliskan kembali method dengan nama yang
sama pada suatu class.
Tujuan : memudahkan penggunaan/ pemanggilan
method dengan fungsionalitas yang
mirip
.
0 6 R E V IS E D 8 FE B 2 0 1 3
Nama method harus sama
Daftar parameter harus berbeda
Return type boleh sama, juga boleh berbeda
Aturan Pendeklarasian Method
E D 8 FE B 2 0 1 3
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.
0 6 R E V IS E D 8 FE B 2 0 1 3
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
E D 8 FE B 2 0 1 3
Contoh Method Overloading
public class Bentuk {
…
public void Gambar(int t1) {
…
}
public void Gambar(int t1, int t2) {
…
}
public void Gambar(int t1, int t2, int t3) {
…
}
public void Gambar(int t1, int t2, int t3, int t4) {
…
}
}
E D 8 FE B 2 0 1 3
0 6 R E V IS E D 8 FE B 2 0 1 3
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
E D 8 FE B 2 0 1 3
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){
…
}
…
}
Method Overloading antara Parent Class
& Sub Class
0 6 R E V IS E D 8 FE B 2 0 1 3
Constructor Overloading
E D 8 FE B 2 0 1 3
0 6 R E V IS E D 8 FE B 2 0 1 3
E D 8 FE B 2 0 1 3
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.
0 6 R E V IS E D 8 FE B 2 0 1 3
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.
Overriding
E D 8 FE B 2 0 1 3
public class Employee { protected String name; protected double Salary; protected Date birthday;
public String getDetails(){ return “Name:
“+name+”\n”+”Salary: “+salary; }
}
public class Manager extends Employee{
protected String department;
public String getDetails(){ return “Name: “+name+”\n”+”Salary: “+salary+”\n”+”Manager of: “+department; } }
Contoh Overriding
0 6 R E V IS E D 8 FE B 2 0 1 3
public class Animal {
public void SetVoice() {
System.out.println(“Blesepblesep”);
}
}
public class Dog extends Animal {
public void SetVoice() {
System.out.println(“Hug hug”);
}
}
E D 8 FE B 2 0 1 3
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.
0 6 R E V IS E D 8 FE B 2 0 1 3
Casting
taking an Object of one particular type and
“turning it into” another Object type
Type Casting
Object Casting
E D 8 FE B 2 0 1 3
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
0 6 R E V IS E D 8 FE B 2 0 1 3
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;
E D 8 FE B 2 0 1 3
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
0 6 R E V IS E D 8 FE B 2 0 1 3
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
E D 8 FE B 2 0 1 3
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
0 6 R E V IS E D 8 FE B 2 0 1 3
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
E D 8 FE B 2 0 1 3
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
0 6 R E V IS E D 8 FE B 2 0 1 3
Example
public class Parent{
public String toString(){
return “this is class Parent”;
}
}
public class ChildA extends Parent{
public String toString(){
return “this is class Child A”;
}
}
public class ChildB extends Parent{
public String toString(){
return “this is class Child B”;
}
}
public class GrandChildA extends ChildA{
public String toString(){
return “this is class Grand Child”;
}
E D 8 FE B 2 0 1 3
Example
> this is method Parent > this is method Child A > this is method Child B > this is method Grand Child
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()); } }
0 6 R E V IS E D 8 FE B 2 0 1 3
Example Upcasting/VMI
> this is method Parent > this is method Child A > this is method Child B > this is method Grand Child
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()); }
E D 8 FE B 2 0 1 3
Example Upcasting/VMI
> this is method Grand Child > this is method Child B
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()); } }
0 6 R E V IS E D 8 FE B 2 0 1 3
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
E D 8 FE B 2 0 1 3
Example
public class Parent{
protected int number = 10;
public String toString(){
return “Parent ” + number;
}
}
public class ChildA extends Parent{
protected int number = 20;
public String toString(){
return “Child A ” + number;
}
public String methodA(){
return “method Child A”;
} }
public class ChildB extends Parent{
protected int number = 30;
public String toString(){
return “Child B ” + number;
}
public String methodB(){
return “method Child B”;
public class GrandChildA extends ChildA{
protected int number = 40;
public String toString(){
return “Grand Child ” + number;
}
public String methodGrand(){
0 6 R E V IS E D 8 FE B 2 0 1 3
Example
> Parent 10 > Child A 20 > Child B 30 > Grand Child 40public 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()); } }
E D 8 FE B 2 0 1 3
Example
> Child A 20 > 10 > Grand Child 40 > 10public 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); } }
0 6 R E V IS E D 8 FE B 2 0 1 3
Example
> method Child Apublic 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; System.out.println(cA.methodA()); castP = cA; System.out.println(castP.methodA()); } }
//compile error:
E D 8 FE B 2 0 1 3
DownCasting
Return the upcasted object back to its original
class object
0 6 R E V IS E D 8 FE B 2 0 1 3
Example
> Grand Child 40 > Compile error > Grand Child 40 > Method Child A> Method Grand Child A > Grand Child 40
> Method Child A
public class Driver{
public static void main(String args[]){ Parent castP;
castP = new GrandChildA();
System.out.println(castP.toString()); System.out.println(castP.methodA());
GrandChildA castG; //castG = castP;
castG = (GrandChildA) castP;
System.out.println(castG.toString()); System.out.println(castG.methodA()); System.out.println(castG.methodGrand()); ChildA castA = (ChildA) castP;
System.out.println(castA.toString()); System.out.println(castA.methodA());
} }
E D 8 FE B 2 0 1 3
Example
> Grand Child 40 > Method Child A> Method Grand Child A
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() ); } }
0 6 R E V IS E D 8 FE B 2 0 1 3
Example
> Child B 30 > ClassCastExceptionpublic class Driver{
public static void main(String args[]){ Parent castP;
ChildA castA; GrandChildA gC;
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
E D 8 FE B 2 0 1 3
Example
> Child A 20 > ClassCastExceptionpublic class Driver{
public static void main(String args[]){ Parent castP;
ChildA castA; GrandChildA gC;
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
0 6 R E V IS E D 8 FE B 2 0 1 3
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
E D 8 FE B 2 0 1 3
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
0 6 R E V IS E D 8 FE B 2 0 1 3
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
E D 8 FE B 2 0 1 3
Example
> Child A 40 >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()); } } }
0 6 R E V IS E D 8 FE B 2 0 1 3
Benefits and Downsides
Flexibility
–
Model Object
Heterogeneous Collection
Polymorphic Arguments
Run-time exception
–
ClassCastException
E D 8 FE B 2 0 1 3
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(); }
0 6 R E V IS E D 8 FE B 2 0 1 3
Example
> 0 Child B 30 > method Child B > 1 Child A 20 > method Child A > 2 Parent 10 > 3 Grand Child 40 > method Child A> method Grand Child A
for(int i = 0; i < 4; i++){
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());
}
E D 8 FE B 2 0 1 3
Polymorphic Arguments/ Subtype
Polymorphism
Polymorphic arguments adalah tipe data suatu
argumen pada suatu method yang bisa menerima
suatu nilai yang bertipe subclass-nya.
0 6 R E V IS E D 8 FE B 2 0 1 3
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);
}
}
0 6 R E V IS E D 8 FE B 2 0 1 3
Exercise
Exercise - Detail
Shapes
- int numSides - String color + Shapes ()
+ Shapes (int numSides, String color) + int getNumSides() + String getColor() + double getArea() + double getPerimeter() + String getDetail() <<interface>> 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()
Triangle - double base
- double height
+ Triangle(int base, int height)
+ Triangle (int numSides, String color, double base, double height)
+ double getEdgeLength() + double getArea()
S -0 1 0 6 R E V IS E D 8 FE B 2 0 1 3
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
di-resizable, maka lakukan resize 0,5 kali. Kemudian
tampilkan perimeter dan area untuk setiap Shape yang
ada di ArrayList.
E D 8 FE B 2 0 1 3
0 6 R E V IS E D 8 FE B 2 0 1 3