this Anahtar Sözcüğü
Bu yazımda this anahtar sözcüğünün kullanımını anlatacağım , bu konuyu daha iyi anlamak için bir önceki yazım Java - Yapılandırıcılar ( Constructors ) konusuna bakmakta fayda var.package com.blogger_project;
class Rectangle {
double width;
double height;
double depth;
Rectangle(final double w, final double h, final double d) {
width = w;
height = h;
depth = d;
}
Rectangle(double w,double h){
width = w;
height = h;
}
Rectangle() {
width = -1;
height = -1;
depth = -1;
}
double volume() {
return width * height * depth;
}
}
package com.blogger_project;
class Rectangle {
double width;
double height;
double depth;
Rectangle(final double width, final double height, final double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Rectangle(double width,double height){
this.width=width;
this.height=height;
}
Rectangle() {
width = -1;
height = -1;
depth = -1;
}
double volume() {
return width * height * depth;
}
}
Burada ki this. ile başlayan değişkenlerin hepsi aslında sınıfın değişkenlerini referans etmektedir.Daha sonra koda baktığımızda anlaşılabilirliği arttırmak için bu yöntem kullanılabilir.
this'in Diğer Kullanımı
this(argüman listesi);
Burada argüman listesine karşılık gelen yapılandırıcı çağrılır.
package com.blogger_project;
package com.blogger_project;
class Rectangle {
double width;
double height;
double depth;
Rectangle(final double width, final double height) {
this.width = width;
this.height = height;
}
Rectangle(final double width, final double height, final double depth) {
this(width, height);
this.depth = depth;
}
Rectangle() {
this(-1, -1, -1);
}
double volume() {
return width * height * depth;
}
}
Bu programda bir önceki program ile aynı işlemi yapar.Üç parametreli constructor çağrıldığında iki parametreli constructor'e göndermede bulunur.1 - Aynı anda hem this() hemde super() kullanılamaz.
2 - Yapılandırıcıya ait herhangi bir değişken kullanılamaz.
0 yorum :