PEMROGRAMAN LANJUT Sistem Informasi PTIIK UB Semester Genap 2014/2015 ABSTRACT CLASS & INTERFACE Dr. Eng. Herman Tolle Program Teknologi Informasi & Ilmu Komputer, Universitas Brawijaya
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. Contoh: public abstract void somemethod();
ABSTRAKSI
Penggunaan class Abstract Class abstract dapat digunakan sebagai superclass 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++; } Movablepoint.class
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 (camelcase). 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 {... }
Contoh Interface
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
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 16
1 // Fig. 10.18: Shape.java Classes that implement Shape 2 // Shape interface declaration. must implement these methods 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 Outline Shape.java 17 Lines 5-7 Classes that implement Shape must implement these methods 2003 Prentice Hall, Inc. All rights reserved.
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 Point implements interface Shape Outline Point.java Line 4 Point implements interface Shape 18 2003 Prentice Hall, Inc. All rights reserved.
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 } 45 Outline Point.java 19 2003 Prentice Hall, Inc. All rights reserved.
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 Outline Point.java Lines 47-59 Implement methods specified by interface Shape 20 2003 Prentice Hall, Inc. All rights reserved.
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 Create Shape array 23 Shape arrayofshapes[] = new Shape[ 3 ]; // create Shape array 24 Outline 21 InterfaceTest.j ava Line 23 Create Shape array 2003 Prentice Hall, Inc. All rights reserved.
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 Outline InterfaceTest.j ava Loop through arrayofshapes to get name, string representation, area and volume of every shape in array Lines 36-42 Loop through arrayofshapes to get name, string representation, area and volume of every shape in array. 22 2003 Prentice Hall, Inc. All rights reserved.
Outline 23 InterfaceTest.j ava 2003 Prentice Hall, Inc. All rights reserved.
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 yang mengimplementasikan penggunaan interface Relation Buat class MovableCircle yang mengimplementasi interface movable
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) Catatan: soal no 2 dikerjakan dan dikumpulkan
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 Catatan: soal no 2 dikerjakan dan dikumpulkan
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; } 32
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 Many methods are declared static 33