Dasar Java : Nested Class – Keuntungan Nested Class

Oleh : Reza Ervani

بسم الله الرحمن الرحيم

Keuntungan dari nested class adalah kita dapat mengelompokkan class-class bersama berdasarkan kesamaan kepemilikannya. Sebenarnya kita sudah melakukan hal itu dengan menempatkan class-class itu dalam satu paket, tetapi menempatkan satu class didalam class lain akan membuatnya menjadi pengelompokan yang lebih kuat.

Suatu nested class umumunya hanya digunakan oleh atau dengan class penaungnya. Terkadang suatu nested class hanya terlihat oleh class penaungnya, hanya digunakan secara internal dan karenanya tidak terlihat diluar class penaung. Tapi di kala yang lain nested class dapat juga terlihat dari luar class penaungnya, tapi hanya dapat digunakan dengan class penaungnya.

Contoh dibawah ini adlah class Cache . Didalam class Cache kita dapat mendeklarasikan class  CacheEntry yang berisi informasi tentang suatu entri cache spesifik (nilai cache, waktu penyisipan, jumlah waktu akses dll). Penggunan class Cache mungkin tidak pernah melihat class CacheEntry , jika mereka tidak perlu untuk mendapatkan informasi terkait CacheEntry itu sendiri, melainkan hanya membutuhkan nilai cache saja. Tapi, class Cache dapat memilih untuk membuat class CacheEntry terlihat dari dunia luar, sehingga mereka dapat mengakses lebih dari hanya sekedar nilai cache-nya saja

Berikut dua kerangka implementasi Cache untuk mengilustrasikan keterangan diatas :

[code language=”java”]

public class Cache {

private Map<String, CacheEntry> cacheMap = new HashMap<String, CacheEntry>();

private class CacheEntry {
public long timeInserted = 0;
public object value = null;
}

public void store(String key, Object value){
CacheEntry entry = new CacheEntry();
entry.value = value;
entry.timeInserted = System.currentTimeMillis();
this.cacheMap.put(key, entry);
}

public Object get(String key) {
CacheEntry entry = this.cacheMap.get(key);
if(entry == null) return null;
return entry.value;
}

}

[/code]

[code language=”java”]

public class Cache {

private Map<String, CacheEntry> cacheMap = new HashMap<String, CacheEntry>();

<b>public</b> class CacheEntry {
public long timeInserted = 0;
public object value = null;
}

public void store(String key, Object value){
CacheEntry entry = new CacheEntry();
entry.value = value;
entry.timeInserted = System.currentTimeMillis();
this.cacheMap.put(key, entry);
}

public Object get(String key) {
CacheEntry entry = this.cacheMap.get(key);
if(entry == null) return null;
return entry.value;
}

public CacheEntry getCacheEntry(String key) {
return this.cacheMap.get(key);
}

}

[/code]

Class cache yang pertama menyembunyikan class CacheEntry,sementara yang kedua membukanya.

About Reza Ervani 426 Articles
Adalah pendiri programming.rezaervani.com -

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.