Pemrograman Berbasis Objek GENERIC. Yuliana Setiowati. Politeknik Elektronika Negeri Surabaya

dokumen-dokumen yang mirip
GENERICS. Yuliana Setiowati. Politeknik Elektronika Negeri Surabaya. Topik

Pemrograman Lanjut. Interface

A. TUJUAN PEMBELAJARAN

Generics. Prepared by Viska Mutiawani. 1

Overriding, Overloading, Polymorphism. Pertemuan 10 Pemrograman Berbasis Obyek Dr. Rodiah

Composition dan Inheritance

Overriding Overloading Polymorphism

Membuat Object Comparable

Pemrograman Berorientasi. Inheritance

Enum. Yuliana Setiowati

1. Keyword mana yang memiliki fungsi sama dengan keyword this dan menyediakan reference ke atribut turunan dari objek? super

Problem 1. Implementasi Interface. Diberikan definisi interface BentukDuaDimensi berikut:

Modul ini mengenalkan Anda konsep dasar mengenai Java generic types.

Boxing & AutoBoxing Java Collection Framework. Collection List Map Set. Generics vs Inheritance

(INHERITANCE) Nurochman

5. Consider the following line of code : byte ohmy What is the range of values that could be assigned to the variable ohmy?

Pemrograman Lanjut. Instance Variable Access Modifier Set dan Get Method

MEMBUAT OBJECT COMPARABLE DAN COMPARATOR

Apa yang menjadi output potongan kode diatas? Error karena tidak ada String yang di-passing kedalam konstruktor Bapak

KONSEP OOP: POLYMORPHISM

Data Structures. Class 5 Pointer. Copyright 2006 by The McGraw-Hill Companies, Inc. All rights reserved.

Konsep Dasar Pemrograman Berorientasi Objek

06/03/2018. Tidak memiliki parameter. Melakukan inisialisasi semua variabel private dengan nilai awal.

KESASTRAAN MELAYU TIONGHOA DAN KEBANGSAAN INDONESIA: JILID 2 FROM KPG (KEPUSTAKAAN POPULER GRAMEDIA)

Operator dan Assignment. Pertemuan 3 Pemrograman Berbasis Obyek

MODUL III ARRAYLIST TUGAS PENDAHULUAN

KONSEP OOP: POLYMORPHISM

1. Manakah jawaban yang benar,pada saat Anda mengcompile dan menjalankan class berikut ini:

OBJECT ORIENTED PROGRAMMING. Day 3 : Operator dan Assignment

Algoritma Pemrograman [BS204]

CSG2H3 Object Oriented Programming. Inheritance -RSM-

E-Book PEMROGRAMAN BERORIENTASI OBJEK. Disusun Oleh: Arfian Hidayat, S.Kom

Dasar Pemrograman Java

Pemrograman Berorientasi. Abstract & Interface

Inheritance. Pertemuan 8 Pemrograman Berbasis Obyek

Overriding. Subclass yang berusaha memodifikasi tingkah laku yang diwarisi dari superclass. Tujuan: subclass memiliki tingkah laku yang lebih

Pemrograman Berbasis Objek Inheritance

Pemrograman Web. Object Oriented Programming in PHP 5

BAHASA PEMROGRAMAN JAVA

Pemrograman Berbasis Obyek. Yuliana Setiowati. Elektronika Negeri Surabaya PJJ PENS-ITS

INTERAKSI ANTAR OBJECT

Reserved words Reserved words atau keywords merupakan kata-kata spesifik digunakan oleh compiler untuk keperluan pemrograman. Contoh reserved words

:: abstract class + interface. :: abstract class

Jobsheet 09. Overloading and Overriding Method

Overriding Overloading Polymorphism

Pemrograman Dasar M E T H O D / F U N G S I

Pemrograman Berbasis Objek Operator dan Assignment

SUKSES BERBISNIS DI INTERNET DALAM 29 HARI (INDONESIAN EDITION) BY SOKARTO SOKARTO

TIF APPLIED MATH 1 (MATEMATIKA TERAPAN 1) Week 3 SET THEORY (Continued)

Like mother, like daughter... [common saying]

RENCANA PEMBELAJARAN SEMESTER PROGRAM STUDI SARJANA TERAPAN TEKNIK INFORMATIKA DEPARTEMEN TEKNIK INFORMATIKA DAN KOMPUTER

Object Oriented Programming (OOP) --Inheritance- Saniati STMIK Teknokrat, Bandar Lampung

Pemrograman Berbasis Objek. Interface. Politeknik Elektronika Negeri Surabaya

Identifier, Keywords, Variabel, Tipe Data Primitif dan Operator PBO. Ramos Somya

Data Structures. Class 4 Arrays. Pengampu : TATI ERLINA, M.I.T. Copyright 2006 by The McGraw-Hill Companies, Inc. All rights reserved.

Algoritma & Struktur Data. Array. Oleh : Nur Hayatin, M.Kom

Inheritance. Topik 5/17/2013

Operator dan Assignment

ANALISIS CAPAIAN OPTIMASI NILAI SUKU BUNGA BANK SENTRAL INDONESIA: SUATU PENGENALAN METODE BARU DALAM MENGANALISIS 47 VARIABEL EKONOMI UNTU

Pemrograman Berorientasi Object. IMade Suartana, S.Kom, M.Kom

PRAKTIKUM 4. Pemrograman Berorientasi Objek

Politeknik Elektronika Negeri Surabaya

Inheritance dan Kata Kunci static

Outline. Struktur Data & Algoritme (Data Structures & Algorithms) Pengantar. Definisi. 2-3 Trees

E VA D A E L U M M A H K H O I R, M. A B. P E R T E M U A N 2 A N A

EFISIENSI JUMLAH ARMADA BUS PATAS AC ANTAR BEBERAPA PERUSAHAAN BERDASARKAN METODE PERTUKARAN TRAYEK DI DKI JAKARTA TESIS

2. Pilih instruksi yang dapat digunakan dalam method actionperformed untuk membedakan antara tombol buttonone dan buttontwo.

1/5. while and do Loops The remaining types of loops are while and do. As with for loops, while and do loops Praktikum Alpro Modul 3.

Pemrograman Berorientasi. Array dan Collections

Pemrograman Lanjut Class, Instance Variable dan Method PTIIK

Nama Soal Pembagian Ring Road Batas Waktu 1 detik Nama Berkas Ringroad[1..10].out Batas Memori 32 MB Tipe [output only] Sumber Brian Marshal

BEKERJA DENGAN JAVA CLASS LIBRARY

Politeknik Elektronika Negeri Surabaya

Statistik Bisnis 1. Week 4 Central Tendency Measures

Praktikum 4 Konsep Inheritance, Polymorphism, dan Encapsulation

Politeknik Elektronika Negeri Surabaya

Abstract Class dan Interface. Viska Mutiawani, M.Sc

POLIMORPHISM PEMROGRAMAN LANJUT. Dr. Eng. Herman Tolle. Sistem Informasi FILKOM UB Semester Genap 2016/2017

MODUL PRAKTIKUM STRUKTUR DATA DAN ALGORITMA GENERIC DAN IMPLEMENTASI COMPARETO()

LINEAR PROGRAMMING-1

Polymorphism (Polimorfisme)

Inheritance (Pewarisan) Pengertian dasar inheritance

Pertemuan 4 Halaman 1/1. Class Inheritance

Polymorphism. Materi ke-8 Pemrograman Berbasis Objek

Pelabelan Pseudo Edge-Magic dan Pseudo Vertex-Magic pada Graf Sebarang

Bahasa Pemrograman :: Polimorfism and Abstraction

Konsep Pemrograman Berorientasi Obyek. Pertemuan 1

Dasar Pemrograman Java

Easy & Simple - Web Programming: Belajar Pemprograman Website Secara Efektif dan Efisien (Indonesian Edition)

Array. Topik. Mendeklarasikan Array Creating Array Initializing Array Array Multidimensional Array Bounds Array Resizing Copying Arrays

Connection Oriented. Kholid F.

Konsep Pemrograman Berorientasi Obyek

A. TUJUAN PEMBELAJARAN 1. Memahami mengenai konsep Enum 2. Memahami bentuk-bentuk penggunaan Enum 3. Memahami fungsi-fungsi yang terdapat di Enum

Object Oriented Programming (OOP) --Polimorphisme-- Saniati STMIK Teknokrat, Bandar Lampung

Pemrograman Lanjut. Class : Deeper Look 2

Pemrograman Lanjut Class and Object PTIIK

Score: 94.0 Persentage: % ~ u ~ Generated by Foxit PDF Creator Foxit Software For evaluation only.

Secuil Cerita tentang Facebook Hacker Cup 2012 Qualification Round [Part II]

Electrostatics. Wenny Maulina

Bahasa Pemrograman 2.

Transkripsi:

GENERIC Yuliana Setiowati

Topik Definisi Generic Non Generic Class Cara mendeklarasikan Type Generic Aturan Penamaan Type Parameter Subtyping Class Generic dengan Dua Type Parameter Generic pada List Nested generic type Raw Types Generic and Collections Menggunakan Interface Generic Comparable Type parameter yang dibatasi Menggunakan? Wildcard Menggunakan Bounded Wildcard dalam Method 2

Generic Generic merupakan cara Java dalam melakukan generalisasi terhadap tipe data tanpa mengurangi kemampuan Java dalam menjaga keamanan penggunaan tipe data.

Penggunaan Generic Generic class declarations Generic interface declarations Generic method declarations Generic constructor declarations. 4

Non Generic Class Pemrograman Berbasis Objek Buatlah object Box, kita bisa memasukkan sembarang object karena parameter pada method add adalah Class Object, tapi pada saat mengambil object tersebut harus diubah sesuai dengan tipe dari object tersebut. Contoh object Box yaitu integerbox diberikan object Integer, pada saat mengambil harus diubah menjadi Integer

Pemrograman Berbasis Objek

Penjelasan Mengapa Error? Pada object IntegerBox dimasukkan object 10 tapi dengan tipe String, tapi pada saat mengambil object, diubah menjadi tipe Integer. Tipe data tidak sesuai sehingga error 7

Permasalahan? Non Generic Class no homogeneous collections memerlukan banyak casting Tidak ada pengecekan pada saat kompile, kesalahan baru bisa terdeteksi pada saat runtime.

Cara mendeklarasikan Class dg Type Generics Ubah class Box menggunakan generics Pemrograman Berbasis Objek Pendeklarasian type generics dengan mengubah public class Box public class Box <T> T biasanya disebut parameter type formal (formal type parameter) T adalah type parameter yang akan diganti dengan tipe sebenarnya (Type dari T bisa berupa class, interface atau tipe variabel lainnya). T adalah nama dari type parameter. Membuat Object atau

Cara mendeklarasikan Pemrograman Berbasis Objek Class dg Type Generics Tidak perlu proses casting pada saat menggunakan fungsi get(). Tapi jika kita menambahkan ke box dengan tipe yang tidak sesuai (misal : String) maka pada saat di kompile akan mengalami error.

Aturan Penamaan Type Parameter Nama type parameter biasanya satu huruf dan huruf besar. Jenis nama tipe parameter yang sering digunakan : E - Element (biasanya digunakan untuk Collection Framework) K Key N Number T - Type V - Value S,U,V dll. - 2nd, 3rd, 4th types

Pemrograman Berbasis Objek

Class Generic dengan Dua Type Parameter Pemrograman Berbasis Objek

Class Generic dengan Dua Type Parameter Pemrograman Berbasis Objek

Class Generic dengan Dua Type Parameter Pemrograman Berbasis Objek

Generics pada List List <E> mylist ; E disebut type variabel, variabel yang diganti dengan type. Jika E adalah class, maka kita bisa melewatkan subclass E. Jika E adalah interface maka kita bisa melewatkan class yang mengimplementasikan E.

Generics List

Nested generic type A generic type is itself a type and can be used as a type variable Cara untuk mendapatkan string dari list pertama :

Type Generic dapat menerima lebih dari satu type variabel

Generics and Collections: ArrayList Pemrograman Berbasis Objek

Subtyping Box<String> gs = new Box<String>(); Box<Object> go = new Box<Object>(); Object O ; String S ; O = go ; O = gs ; go = gs ; //error karena Box<String> bukan subtype dari Box<Object> G<Object> ga ; G<String> gb; ga = gb // error karena G<String> bukan subtype dari G<Object> Secara umum jika B adalah dari A dan G adalah suatu tipe data generics maka tidak berarti G<B> adalah subtype dari G<A>. 21

Subtype FujiApple is a subtype of Apple Apple is a subtype of Fruit FujiApple is a subtype of Fruit. 22

Subtype Manakah program yang error? Apple a = new Apple(); Fruit f = a; List<Apple> apples; List<Fruit> fruits ; apples = fruits; 23

Raw Types Java membolehkan class generic digunakan tanpa type argument.

Penggunaan Generic pada Interface Comparable

Penggunaan Generic pada Interface Comparable

Penggunaan Generic Pemrograman Berbasis Objek pada Interface Comparable Class Person terdapat dua variabel yaitu firstname dan surname, untuk mengurutkan data maka class Person harus mengimplementasikan interface Comparable dan mengimplementasikan method compareto(). Data2 pada class Person diurutkan berdasarkan surname, tetapi jika surname sama maka data diurutkan berdasarkan firstname

Memasukan beberapa object Person pada object array author, selanjutnya data pada array tersebut diurutkan berdasarkan surname

Type parameter yang dibatasi (bounded type parameter) Jika kita ingin memberikan batasan type yang diperbolehkan untuk dilewatkan ke type parameter. Contoh method dengan parameter number, hanya menerima object dari class Number dan subclass. Hal ini yang disebut bounded type parameter. Cara <U extends Number> Jika terdapat interface yang harus diimplementasikan gunakan & <U extends Number & MyInterface> Tidak boleh menggunakan super

Yang menjadi parameter dari method inspect() adalah semua object yang merupakan anak dari class Number

Generic Method

Generic Constructor Yang menjadi parameter dari method inspect() adalah semua object yang merupakan anak dari class Number misal object Integer, Float, Double

Pemrograman Berbasis Objek

Type parameter yang dibatasi

Penggunaan? Wildcard Simbol? disebut wildcard, menyatakan an unknown type.

Penggunaan? Wildcard public abstract class Animal { public abstract void playwith(collection<animal> playgroup); } public class Dog extends Animal { public void playwith(collection<animal> playgroup) { } } Collection<Dog> dogs = new ArrayList<Dog>(); Dog adog = new Dog(); adog.playwith(dogs); //ERROR The Animal class has a playwith() method that accepts a Collection of Animals. The Dog, which extends Animal, overrides this method. Let s try to use the Dog class in an example. Here, I create an instance of Dog and send a Collection of Dogs to its playwith() method. We get a compilation error: Error: line (29) cannot find symbol method playwith(java.util.collection<com.agiledeveloper.dog>) This is because a Collection of Dogs can t be treated as a Collection of Animals which the playwith() method expects. However, it would make sense to be able to send acollection of Dogs to this method, isn t it? How can we do that? This is where the wildcard or unknown type comes in. 36

Penggunaan? Wildcard We modify both the playmethod() methods (in Animal and Dog) as follows: public void playwith(collection<?> playgroup) The Collection is not of type Animal. Instead it is of unknown type (?). Unknown type is not Object, it is just unknown or unspecified. Now, the code: adog.playwith(dogs); compiles with no error. 37

Penggunaan? Wildcard There is a problem however. We can also write: ArrayList<Integer> numbers = new ArrayList<Integer>(); adog.playwith(numbers); The change I made to allow a Collection of Dogs to be sent to the playwith() method now permits acollection of Integers to be sent as well. If we allow that, that will become one weird dog. How can we say that the compiler should allow Collections of Animals or Collections of any type that extends Animal, but not anycollection of other types? This is made possible by the use of upper bounds as shown below: public void playwith(collection<? extends Animal> playgroup) One restriction of using wildcards is that you are allowed to get elements from a Collection<?>, but you can t add elements to such a collection the compiler has no idea what type it is dealing with. 38

list1 mengacu ke List dengan tipe java.lang.object dan list2 mengacu ke List String. Meskipun String merupakan subclass dari Object, List<String> tidak ada hubungannya dengan List<Object>, sehingga melewatkan List<String> ke method yang memiliki parameter List<Object> akan menyebabkan error.

Penggunaan? Wildcard Bagaimana penyelesaiannya? Menggunakan? Wildcard. List<?> berarti list dengan object unknown type

Penggunaan? Wildcard Illegal menggunakan wildcard pada saat create type generic. Jika list bisa menerima sembarang object, gunakan class Object sebagai type variabel.

Penggunaan? Wildcard

Pemrograman Berbasis Objek

Penggunaan Bounded Wildcard dalam Method Sintak upper bound untuk wildcard: GenericType <? extends upperboundtype> Contoh : List <? extends Number> Berarti kita bisa melewatkan object dari List<Integer>, List<Double>, List<Float> Sintak lower bound untuk wildcard: GenericType <? super Integer> berarti kita bisa melewatkan List<Integer> atau list yang berisi object yang merupakan superclass dari class Integer.

Lower Bounded Wildcards Assume we want to copy elements from one collection to another. Here is my first attempt for a code to do that: public static <T> void copy(collection<t> from, Collection<T> to) { } Let s try using this method: ArrayList<Dog> doglist1 = new ArrayList<Dog>(); ArrayList<Dog> doglist2 = new ArrayList<Dog>(); // copy(doglist1, doglist2); In this code, we are copying Dogs from one Dog ArrayList to another. 45

Lower Bounded Wildcards Since Dogs are Animals, a Dog may be in both a Dog s ArrayList and an Animal s ArrayList, isn t it? So, here is the code to copy from a Dog s ArrayList to an Animal s ArrayList. ArrayList<Dog> doglist1 = new ArrayList<Dog>(); ArrayList<Animal> animallist = new ArrayList<Animal>(); copy(doglist1, animallist); This code, however, fails compilation with error: Error: line (36) <T>copy(java.util.Collection<T>,java.util.Collection<T>) in com.agiledeveloper.test cannot be applied to (java.util.arraylist<com.agiledeveloper.dog>, java.util.arraylist<com.agiledeveloper.animal>) 46

Lower Bounded Wildcards How can we make this work? This is where the lower bounds come in. Our intent for the second argument of Copy is for it to be of either type T or any type that is a base type of T. Here is the code: public static <T> void copy(collection<t> from, Collection<? super T> to) Here we are saying that the type accepted by the second collection is the same type as T is, or its super type. 47

Penggunaan Upper Bounded Wildcard dalam Method

Upper Bounded Wildcard

Upper Bounded Wildcard

Upper Bounded Wildcard