PEMROGRAMAN LANJUT
Program Teknologi Informasi & Ilmu Komputer, Universitas Brawijaya
ABSTRACT CLASS &
INTERFACE
Dr. Eng. Herman Tolle
Sistem Informasi PTIIK UB Semester Genap 2014/2015
ABSTRACT
• Abstract Class (Abstraksi) adalah kelas yang memiliki satu atau lebih method yang belum didefinisikan
• Method dalam class abstract yang tidak
mempunyai implementasi dinamakan method
abstract.
• Untuk membuat method abstract, cukup menulis deklarasi method tanpa isi tubuh class dan
digunakan menggunakan kata kunci abstract.
Penggunaan class Abstract
• Class abstract dapat digunakan sebagaisuperclass untuk satu atau lebih sub class
(kelas turunan)
• Method abstract didefinisikan pada class abstract sebagai definisi umum saja, yang harus didetailkan / diimplementasikan pada kelas turunannya.
INTERFACE
• Interface adalah sebuah blok (setingkat class) yang hanya berisi signature method dan
constant (konstanta)
• Signature method dapat dianggap seperti
sebuah abstract method. Method yang tidak memiliki implementasi tetapi hanya berupa nama method saja
public interface Movable { public void moveUp(); public void moveDown(); public void moveLeft(); public void moveRight(); }
public class MovablePoint implements Movable { // Private member variables
private int x, y; // (x, y) coordinates of the point // Constructor
public MovablePoint(int x, int y) { this.x = x; this.y = y;
}
@Override
public String toString() {
return "Point at (" + x + "," + y + ")"; }
// Implement abstract methods defined in the interface Movable
@Override
public void moveUp() { y--; }
@Override
public void moveDown() { y++; }
@Override
public void moveLeft() { x--; }
@Override
public void moveRight() { x++; } }
public class TestMovable {
public static void main(String[] args) {
Movable m1 = new MovablePoint(5, 5); // upcast System.out.println(m1); m1.moveDown(); System.out.println(m1); m1.moveRight(); System.out.println(m1); } }
Implementasi Interface
• Menggunakan kata kunci IMPLEMENTS
• public class MovablePoint implements
Movable
• Class hanya dapat mengEXTEND SATU superclass, tetapi dapat mengIMPLEMENTASIkan BANYAK
interface.
• Ketika class mengimplementasikan sebuah interface, selalu pastikan bahwa semua method dalam interface telah diimplementasikan semuanya pada class tsb, jika tidak, akan ada pesan kesalahan
• Line.java:4: Line is not abstract and does not override abstract
Kapan menggunakan interface?
• Kita menggunakan interface jika kita ingin class yang tidak berhubungan mengimplementasikan method atau fungsi-fungsi yang sama.
• Melalui interface kita dapat menangkap kemiripan diantara class yang tidak
berhubungan
• Sebuah Class dapat mengimplementasikan lebih dari satu interface.
Interface Naming Convention
• Use an adjective (typically ends with "able") consisting of one or more words.
• Each word shall be initial capitalized (camel-case).
• Forexample: Serializable, Extenalizable, Movable, Clonable, Runnable, etc.
Pewarisan Antar Interface
• Interface bukan bagian dari hirarki class.
• Interface dapat mempunyai hubungan pewarisan antara mereka sendiri.
• Contohnya, misal kita punya dua interface StudentInterface dan
PersonInterface. Jika StudentInterface meng-extend
PersonInterface, maka ia akan mewariskan semua deklarasi method dalam PersonInterface.
public interface PersonInterface { . . .
}
public interface StudentInterface extends PersonInterface { . . .
Catatan
• Interface dapat diturunkan dari satu atau lebih interface
interface Hockey extends Sports, Event
• Class dapat mengimplement lebih dari satu
Class PersegiPanjang implements Relation, Movable, Resizable
16
10.8 Case Study: Creating and Using
Interfaces
• Use interface Shape
– Replace abstract class Shape
• Interface
– Declaration begins with interface keyword – Classes implement an interface (and its
methods)
– Contains public abstract methods
• Classes (that implement the interface) must implement these methods
2003 Prentice Hall, Inc. All rights reserved.
Outline 17 Shape.java Lines 5-7 Classes that implement Shape must implement these methods
1 // Fig. 10.18: Shape.java
2 // Shape interface declaration.
3
4 public interface Shape {
5 public double getArea(); // calculate area
6 public double getVolume(); // calculate volume
7 public String getName(); // return shape name
8
9 } // end interface Shape
Classes that implement Shape must implement these methods
2003 Prentice Hall, Inc. All rights reserved.
Outline 18 Point.java Line 4 Point implements interface Shape 1 // Fig. 10.19: Point.java
2 // Point class declaration implements interface Shape.
3
4 public class Point extends Object implements Shape {
5 private int x; // x part of coordinate pair
6 private int y; // y part of coordinate pair
7
8 // no-argument constructor; x and y default to 0
9 public Point()
10 {
11 // implicit call to Object constructor occurs here
12 }
13
14 // constructor
15 public Point( int xValue, int yValue )
16 {
17 // implicit call to Object constructor occurs here
18 x = xValue; // no need for validation
19 y = yValue; // no need for validation
20 }
21
22 // set x in coordinate pair
23 public void setX( int xValue )
24 {
25 x = xValue; // no need for validation
26 }
27
2003 Prentice Hall, Inc. All rights reserved.
Outline
19
Point.java
28 // return x from coordinate pair
29 public int getX()
30 {
31 return x;
32 }
33
34 // set y in coordinate pair
35 public void setY( int yValue )
36 {
37 y = yValue; // no need for validation
38 }
39
40 // return y from coordinate pair
41 public int getY()
42 {
43 return y;
44 }
2003 Prentice Hall, Inc. All rights reserved.
Outline 20 Point.java Lines 47-59 Implement methods specified by interface Shape
46 // declare abstract method getArea
47 public double getArea()
48 {
49 return 0.0;
50 }
51
52 // declare abstract method getVolume
53 public double getVolume()
54 {
55 return 0.0;
56 }
57
58 // override abstract method getName to return "Point"
59 public String getName()
60 {
61 return "Point";
62 }
63
64 // override toString to return String representation of Point
65 public String toString()
66 {
67 return "[" + getX() + ", " + getY() + "]";
68 }
69
70 } // end class Point
Implement methods specified by interface Shape
2003 Prentice Hall, Inc. All rights reserved.
Outline
21
InterfaceTest.j ava
Line 23
Create Shape array
1 // Fig. 10.20: InterfaceTest.java
2 // Test Point, Circle, Cylinder hierarchy with interface Shape.
3 import java.text.DecimalFormat;
4 import javax.swing.JOptionPane;
5
6 public class InterfaceTest {
7
8 public static void main( String args[] )
9 {
10 // set floating-point number format
11 DecimalFormat twoDigits = new DecimalFormat( "0.00" );
12
13 // create Point, Circle and Cylinder objects
14 Point point = new Point( 7, 11 );
15 Circle circle = new Circle( 22, 8, 3.5 );
16 Cylinder cylinder = new Cylinder( 20, 30, 3.3, 10.75 );
17
18 // obtain name and string representation of each object
19 String output = point.getName() + ": " + point + "\n" +
20 circle.getName() + ": " + circle + "\n" +
21 cylinder.getName() + ": " + cylinder + "\n";
22
23 Shape arrayOfShapes[] = new Shape[ 3 ]; // create Shape array
24
2003 Prentice Hall, Inc. All rights reserved.
Outline 22 InterfaceTest.j ava Lines 36-42 Loop through arrayOfShapes to get name, string
representation, area and volume of every shape in array.
25 // aim arrayOfShapes[ 0 ] at subclass Point object
26 arrayOfShapes[ 0 ] = point;
27
28 // aim arrayOfShapes[ 1 ] at subclass Circle object
29 arrayOfShapes[ 1 ] = circle;
30
31 // aim arrayOfShapes[ 2 ] at subclass Cylinder object
32 arrayOfShapes[ 2 ] = cylinder;
33
34 // loop through arrayOfShapes to get name, string
35 // representation, area and volume of every Shape in array
36 for ( int i = 0; i < arrayOfShapes.length; i++ ) {
37 output += "\n\n" + arrayOfShapes[ i ].getName() + ": " +
38 arrayOfShapes[ i ].toString() + "\nArea = " +
39 twoDigits.format( arrayOfShapes[ i ].getArea() ) +
40 "\nVolume = " +
41 twoDigits.format( arrayOfShapes[ i ].getVolume() );
42 }
43
44 JOptionPane.showMessageDialog( null, output ); // display output
45
46 System.exit( 0 );
47
48 } // end main
49
50 } // end class InterfaceTest
Loop through arrayOfShapes to get name, string representation, area and volume of every shape in array
2003 Prentice Hall, Inc. All rights reserved.
Outline
23
InterfaceTest.j ava
Contoh Kasus
• Ada 2 class: class Line dan class MyInteger
• class Line berisi method yang menghitung panjang dari garis dan membandingkan object Line ke object dari class yang sama.
• Class MyInteger berisi method yang membandingkan object
MyInteger ke object dari class yang sama.
• Kedua class mempunyai method yang hampir sama, yaitu memperbandingkan dua object lain dalam tipe yang sama. • Supaya dapat menjalankan cara untuk memastikan bahwa
dua class-class ini mengimplementasikan beberapa method dengan fungsi yang sama, kita dapat menggunakan sebuah
interface
• untuk hal ini. Kita dapat membuat sebuah class interface, katakanlah interface Relation dimana mempunyai deklarasi method untuk fungsi-fungsi pembandingan.
public interface Relation {
public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b); }
public class Line implements Relation {
private double x1; private double x2; private double y1; private double y2;
private String nama;
public Line(double x1, double x2, double y1, double y2, String name){
this.x1 = x1; this.x2 = x2; this.y1 = y1;
this.y2 = y2; this.nama = name; }
public double getLength(){
double length = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)* (y2-y1));
return length; }
public boolean isGreater( Object a, Object b){ double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength(); return (aLen > bLen);
}
public boolean isLess( Object a, Object b){ double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength(); return (aLen < bLen);
}
public boolean isEqual( Object a, Object b){ double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength(); return (aLen == bLen);
} }
Latihan
• Buat Class MyInteger yangmengimplementasikan penggunaan interface
Relation
• Buat class MovableCircle yang
Latihan
1. Buat Kode Program untuk menentukan mana garis terpanjang dan mana garis terpendek dari input 3 buah objek garis (Line)
2. Buat Class dan Program seperti kasus di atas untuk objek Persegi Panjang (atribut: X1, X2, Y1, Y2)
File 1: Relation.java File 2: Line.java
File 3: TestLine.java
// file 3: TestLine.java
public static void main() {
Line LineA = new Line(3,7,8,4,”GarisA”); Line LineB = new Line(-2,2,2,-2,”GarisB”); Line LineC = new Line(10,13,3,-2,”GarisC”); Line Max = new Line(0,0,0,0,”max”);
Max = LineA;
If Max.isGreater(LineB, Max) Max = LineB;
If Max.isGreater(LineC, Max) Max = LineC;
System.out.println(“Garis terpanjang adalah = “ + Max.getName());
Latihan F
1. Buat Kode Program untuk menentukan mana garis terpanjang dan mana garis terpendek dari input 3 buah objek garis (Line)
2. Buat Class dan Program seperti kasus di atas untuk objek Persegi Panjang (atribut: X1, X2, Y1, Y2), mencari objek TERLUAS dari input 3 buah objek Persegi
32
10.8 Case Study: Creating and Using
Interfaces (Cont.)
• Implementing Multiple Interface
– Provide common-separated list of interface names after keyword implements
• Declaring Constants with Interfaces
– public interface Constants {
public static final int ONE = 1; public static final int TWO = 2; public static final int THREE = 3;
33
10.10 Type-Wrapper Classes for
Primitive Types
• Type-wrapper class
– Each primitive type has one
• Character, Byte, Integer, Boolean, etc.
– Enable to represent primitive as Object
• Primitive types can be processed polymorphically
– Declared as final