Session4 Polymorphism
Session4 Polymorphism
Polymorphism
Session 4
Learning Outcomes
Outline
• Introduction
• Types of polymorphism
• Implementing Polymorphism
• Casting object
• The instanceof Operator
• The ArrayList Class
Introduction
• What is Polymorphism and why do we need that?
• Static Polymorphisme
class DisplayOverload {
public void show(int num) {
public class
System.out.println("Display an integer: " + num); StaticPolymorphismExample {
}
public static void main(String[]
public void show(String str) {
args) {
System.out.println("Display a string: " + str);
} DisplayOverload obj = new
public void show(byte num) {
DisplayOverload();
System.out.println("Display a byte: " + num);
obj.show(5);
}
obj.show("Hello Polymorphism");
public void show(int num1, double num2) {
System.out.println("Display an integer and a double: " + num1 + obj.show(100, 123.456);
", " + num2);
} obj.show(123.456, 100);
public void show(double num2, int num1) {
obj.show((byte) 101); // Explicitly
System.out.println("Display a double and an integer: " + num2 + casting to match the byte parameter
", " + num1);
}
method
// ... you can add more overloaded methods with different
}
parameter lists }
}
Types of Polymorphism
2) Dynamic Polymorphism
• This can be achieved by
1) overriding a particular method of the superclass
2) Implementing Abstract
3) Implementing Interface
• As the method to call is determined at runtime
• It is known as well as dynamic binding
Dynamic Polymorphism (1)
• Example – Overriding a particular method of the superclass
// abstract method to describe the shape @Override The classes Circle and
double area() {
abstract String describe();
return width * height; Rectangle extend Shape
// non-abstract method
String getColor() {
}
and provide concrete
}
return color; @Override
String describe() { implementations for these
} return "A rectangle with width " + width + " and
height " + height + " and color " + getColor(); methods.
class Circle extends Shape { }
double radius; }
Circle(String color, double radius) { public class TestShapes { When methods like
super(color);
this.radius = radius;
public static void main(String[] args) {
Shape shape1 = new Circle("Red", 2.2); describe() and area() are
} Shape shape2 = new Rectangle("Blue", 2, 3);
called on a Shape reference
@Override
double area() {
System.out.println(shape1.describe());
System.out.println("Area: " + shape1.area());
pointing to a Circle or
}
return Math.PI * Math.pow(radius, 2);
System.out.println(shape2.describe());
Rectangle object, the
@Override }
System.out.println("Area: " + shape2.area());
corresponding method for
String describe() {
return "A circle with radius " + radius + " and color " +
}
the actual object type
getColor();
}
(Circle or Rectangle) is
} executed at runtime.
Dynamic Polymorphism (6)
• Example – Interface Class
• Consist only of constants and abstract methods
• Can not make an object with the new operator
• Create a subclass that has more than one superclass
(Multiple inheritance solution)
• Not inherited but implemented
• Declared using keyword interface
• In subclass using keyword implements
Dynamic Polymorphism (7)
• Example – Interface Class
• Each interface is compiled into bytecode lines, just
like regular class
• All method declared in interface should be
overridden by implementing class
Dynamic Polymorphism (8)
• Example – Implementing Interface Class
• interface Animal { //Declare interface class
public void eat(); //Abstract method
public void travel(); //Abstract method
}
• public class Mammal implements Animal { //Using implement if you want
// to use interface class Shape
public void eat() { //Function in interface class Animal
// should be overridden in subclass point
System.out.println("Mammal eats");
}
Abstract Konkrit
abstract class Kendaraan { class Kendaraan {
abstract void bergerak(); void bergerak() {
} System.out.println("Kendaraan bergerak.");
}
class Mobil extends Kendaraan { }
void bergerak() {
class Mobil extends Kendaraan {
System.out.println("Mobil berjalan di jalan raya."); @Override
} void bergerak() {
} System.out.println("Mobil berjalan di jalan raya.");
}
class Perahu extends Kendaraan { }
void bergerak() {
class Perahu extends Kendaraan {
System.out.println("Perahu berlayar di laut.");
@Override
} void bergerak() {
} System.out.println("Perahu berlayar di laut.");
}
public class Main { }
public static void main(String[] args) {
Kendaraan mobil = new Mobil(); public class Main { public static void main(String[] args)
Kendaraan perahu = new Perahu(); { Kendaraan kendaraan = new Kendaraan(); // Error: Kendaraan
adalah kelas abstrak dan tidak bisa diinstansiasi
mobil.bergerak(); // Output: Mobil berjalan di jalan raya. Kendaraan mobil = new Mobil(); // Ini benar, karena Mobil
perahu.bergerak(); // Output: Perahu berlayar di laut. adalah subkelas konkret dari Kendaraan mobil.bergerak(); //
} Output akan benar: Mobil berjalan di jalan raya. } }
}
Pada baris Kendaraan kendaraan = new Kendaraan(); akan terjadi error kompilasi karena Kendaraan adalah kelas
abstrak. Java melarang pembuatan objek langsung dari kelas abstrak karena kelas abstrak biasanya tidak memiliki
implementasi lengkap. Kesalahan ini memaksa kita untuk hanya membuat objek dari kelas-kelas konkret yang telah
menyediakan implementasi untuk semua metode abstraknya. Ini adalah bagaimana Java menerapkan konsep
polimorfisme dinamis melalui kelas abstrak.
Interface VS Abstract Class
Casting Object (1)
• Converting an object from a class to other
type class in an inheritance hierarchy
• There are 2 kind of Casting Object :
1. Implicit Casting
Object obj = new MountainBike();
2. Explicit Casting
MountainBike myBike = (MountainBike) obj;
• Error if:
Student b = o;
• Because a student object is an instance of Object, but
an Object is not necessarily an instance of Student.
Casting Object (2)
• To ensure that the object is an instance of
another object before attempting a casting
• Object myObject = new Circle();
//Peform casting if myObject is an instance of Circle
if (myObject instanceof Circle){
system.out.println("This is an instance of Circle")
}
ArrayList
• To construct ArrayList :
ArrayList<String> cityList = new ArrayList<String>();
// Constructor
// Constructor
public Bicycle(int gear, int speed) {
public MountainBike(int gear, int speed, int startHeight) {
this.gear = gear;
this.speed = speed; super(gear, speed);
} seatHeight = startHeight;
}
// Metode untuk meningkatkan kecepatan sepeda
public void speedUp(int increment) { // Metode khusus untuk MountainBike
speed += increment; public void setSeatHeight(int newHeight) {
} seatHeight = newHeight;
}
// Metode untuk mengurangi kecepatan sepeda
public void applyBrake(int decrement) {
// Getter untuk seatHeight
speed -= decrement;
public int getSeatHeight() {
}
return seatHeight;
// Getter dan Setter }
public int getGear() { }
return gear;
} // Kelas utama untuk menunjukkan casting objek
public class Main {
public void setGear(int gear) { public static void main(String[] args) {
this.gear = gear; // Implicit casting ke Bicycle
}
Bicycle bike = new MountainBike(3, 100, 25);
// Bicycle.java
// Kelas Bicycle dengan atribut gear dan speed beserta setter dan getter-nya
// MountainBike.java
// Kelas MountainBike menambahkan atribut
public class Bicycle {
private int gear; seatHeight
private int speed;
// Implicit casting terjadi ketika sebuah
public Bicycle(int gear, int speed) { MountainBike dianggap sebagai Bicycle
this.gear = gear;
this.speed = speed;
}
public class MountainBike extends Bicycle {
// Method untuk meningkatkan kecepatan sepeda private int seatHeight;
public void speedUp(int increment) {
speed += increment;
}
public MountainBike(int gear, int speed, int
// Method untuk mengurangi kecepatan sepeda startHeight) {
public void applyBrake(int decrement) {
speed -= decrement; super(gear, speed);
}
seatHeight = startHeight;
// Getter untuk gear }
public int getGear() {
return gear;
}
// Method untuk mengatur tinggi seat
// Setter untuk gear
public void setGear(int gear) {
public void setSeatHeight(int newHeight) {
this.gear = gear; seatHeight = newHeight;
}
}
// Getter untuk speed
public int getSpeed() {
return speed; // Getter untuk seatHeight
}
public int getSeatHeight() {
// Setter untuk speed
public void setSpeed(int speed) { return seatHeight;
}
this.speed = speed;
}
} }
Setiap file di atas harus disimpan dengan nama yang sesuai (Bicycle.java, MountainBike.java, Main.java) dalam direktori yang sama. Untuk menjalankan program
ini, Anda harus mengkompilasi setiap file dan menjalankan Main.java:
// Main.java
// File utama yang menggabungkan semua komponen dan menunjukkan implicit dan explicit
casting
import java.util.ArrayList;
// Kita tidak perlu cast secara eksplisit untuk mengakses metode dari tipe Bicycle
bike.speedUp(10); // Bekerja karena speedUp ada di Bicycle
Bina Nusantara