What is “this” ? Java OOP

3 Jun

Dalam setiap methods non static yang dipanggil lewat suatu objek, terdapat secara implicit suatu variable reference yang bernama “this”.

“this” menunjuk ke objek yang memanggil methods itu.
Contoh constructor yang memakai this:


public class Lingkaran {
public double x, y, r ; // pusat dan jari-jari
public Lingkaran (double x, double y, double r){
this.x = x; this.y = y; this.r = r;
public double luas() { return 3.14 * r * r; }
}

Contoh class Lingkaran dengan banyak constructor :


public class Lingkaran {
public double x, y, r;
public Lingkaran(double x, double y, double r){
this.x = x; this.y = y; this.r = r;
}
public Lingkaran (double r){
x = 0.0; y = 0.0; this.r = r;
}
public Lingkaran(Lingkaran lk){
x = lk.x; y=lk.y; r = lk.r;
}
public Lingkaran(){
x=0.0; y = 0.0; r = 1.0;
}
public double luas() { return 3.14*r*r; }
}

Pendefinisian class Lingkaran itu dapat disingkat dengan memakai this sebagai berikut:


public class Lingkaran {
public double x, y, r;
public Lingkaran(double x, double y, double r){
this.x = x; this.y = y; this.r = r;
}
public Lingkaran (double r){ this(0.0, 0.0, r); }
public Lingkaran(Lingkaran lk){ this(lk.x, lk.y, lk.r); }
public Lingkaran(){ this(0.0, 0.0, 1.0); }
public double luas() { return 3.14 * r * r; }
}

Pengunaan this untuk memanggil contructor lain seperti tadi harus muncul sebagai statement pertama dalam body constructor.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: