Bu yazıda, Java'da bu anahtar kelimeyi, nasıl ve nerede kullanılacağını örnekler yardımıyla öğreneceğiz.
bu Anahtar Kelime
Java'da bu anahtar sözcük, bir yöntem veya yapıcı içindeki geçerli nesneye başvurmak için kullanılır. Örneğin,
class Main ( int instVar; Main(int instVar)( this.instVar = instVar; System.out.println("this reference = " + this); ) public static void main(String() args) ( Main obj = new Main(8); System.out.println("object reference = " + obj); ) )
Çıktı :
bu referans = Ana @ 23fc625e nesne referansı = Ana @ 23fc625e
Yukarıdaki örnekte, Main sınıfından obj adında bir nesne oluşturduk. Daha sonra obj ve this
sınıfın anahtar kelimesine referansı yazdırıyoruz .
Burada hem obj hem de referansın this
aynı olduğunu görebiliriz. Bunun geçerli nesneye yapılan referanstan başka bir şey olmadığı anlamına gelir.
Bu Anahtar Kelimenin Kullanımı
this
Anahtar kelimenin yaygın olarak kullanıldığı çeşitli durumlar vardır .
Bunu Belirsizlik Değişken Adları için Kullanma
Java'da, bir kapsam içinde aynı ada sahip iki veya daha fazla değişkenin (sınıf kapsamı veya yöntem kapsamı) bildirilmesine izin verilmez. Ancak, örnek değişkenler ve parametreler aynı ada sahip olabilir. Örneğin,
class MyClass ( // instance variable int age; // parameter MyClass(int age)( age = age; ) )
Yukarıdaki programda, örnek değişkeni ve parametre aynı ada sahiptir: yaş. Burada Java derleyicisinin ad belirsizliğinden dolayı kafası karışmıştır.
Böyle bir durumda bu anahtar kelimeyi kullanırız. Örneğin,
Öncelikle this
anahtar kelime kullanmadan bir örnek görelim :
class Main ( int age; Main(int age)( age = age; ) public static void main(String() args) ( Main obj = new Main(8); System.out.println("obj.age = " + obj.age); ) )
Çıktı :
mc.age = 0
Yukarıdaki örnekte, kurucuya 8
bir değer olarak geçtik . Ancak 0
çıktı olarak alıyoruz . Bunun nedeni, örnek değişken ile parametre arasındaki adlardaki belirsizlik nedeniyle Java derleyicisinin kafasının karışmasıdır.
Şimdi yukarıdaki kodu this
anahtar kelime kullanarak yeniden yazalım .
class Main ( int age; Main(int age)( this.age = age; ) public static void main(String() args) ( Main obj = new Main(8); System.out.println("obj.age = " + obj.age); ) )
Çıktı :
obj.age = 8
Şimdi, beklenen çıktıyı alıyoruz. Bunun nedeni, kurucu çağrıldığında, this
kurucunun içinde kurucuyu çağıran nesne obj ile değiştirilmesidir. Bu nedenle yaş değişkenine 8 değeri atanmıştır.
Ayrıca, parametrenin ve örnek değişkeninin adı farklıysa, derleyici bu anahtar kelimeyi otomatik olarak ekler. Örneğin, kod:
class Main ( int age; Main(int i) ( age = i; ) )
eşdeğerdir:
class Main ( int age; Main(int i) ( this.age = i; ) )
Bu Getters and Setters ile
this
Anahtar kelimenin başka bir yaygın kullanımı , bir sınıfın ayarlayıcı ve alıcı yöntemleridir. Örneğin:
class Main ( String name; // setter method void setName( String name ) ( this.name = name; ) // getter method String getName()( return this.name; ) public static void main( String() args ) ( Main obj = new Main(); // calling the setter and the getter method obj.setName("Toshiba"); System.out.println("obj.name: "+obj.getName()); ) )
Çıktı :
obj.name: Toshiba
Burada this
anahtar kelime kullandık :
- ayarlayıcı yöntemi içinde değer atamak için
- alıcı yöntemi içindeki değere erişmek için
Bunu Yapıcı Aşırı Yüklemede Kullanma
Yapıcı aşırı yüklemesi ile çalışırken, başka bir kurucudan bir kurucu çağırmamız gerekebilir. Böyle bir durumda, kurucuyu açıkça arayamayız. Bunun yerine this
anahtar kelime kullanmalıyız .
Burada, bu anahtar kelimenin farklı bir biçimini kullanıyoruz. Yani this()
,. Bir örnek alalım
class Complex ( private int a, b; // constructor with 2 parameters private Complex( int i, int j )( this.a = i; this.b = j; ) // constructor with single parameter private Complex(int i)( // invokes the constructor with 2 parameters this(i, i); ) // constructor with no parameter private Complex()( // invokes the constructor with single parameter this(0); ) @Override public String toString()( return this.a + " + " + this.b + "i"; ) public static void main( String() args ) ( // creating object of Complex class // calls the constructor with 2 parameters Complex c1 = new Complex(2, 3); // calls the constructor with a single parameter Complex c2 = new Complex(3); // calls the constructor with no parameters Complex c3 = new Complex(); // print objects System.out.println(c1); System.out.println(c2); System.out.println(c3); ) )
Çıktı :
2 + 3i 3 + 3i 0 + 0i
Yukarıdaki örnekte, this
anahtar kelime kullandık ,
- kurucusunu çağırmak için
Complex(int i, int j)
kurucusundanComplex(int i)
- kurucusunu çağırmak için
Complex(int i)
kurucusundanComplex()
Çizgiye dikkat edin,
System.out.println(c1);
Here, when we print the object c1, the object is converted into a string. In this process, the toString()
is called. Since we override the toString()
method inside our class, we get the output according to that method.
One of the huge advantages of this()
is to reduce the amount of duplicate code. However, we should be always careful while using this()
.
This is because calling constructor from another constructor adds overhead and it is a slow process. Another huge advantage of using this()
is to reduce the amount of duplicate code.
Note: Invoking one constructor from another constructor is called explicit constructor invocation.
Passing this as an Argument
We can use this
keyword to pass the current object as an argument to a method. For example,
class ThisExample ( // declare variables int x; int y; ThisExample(int x, int y) ( // assign values of variables inside constructor this.x = x; this.y = y; // value of x and y before calling add() System.out.println("Before passing this to addTwo() method:"); System.out.println("x = " + this.x + ", y = " + this.y); // call the add() method passing this as argument add(this); // value of x and y after calling add() System.out.println("After passing this to addTwo() method:"); System.out.println("x = " + this.x + ", y = " + this.y); ) void add(ThisExample o)( o.x += 2; o.y += 2; ) ) class Main ( public static void main( String() args ) ( ThisExample obj = new ThisExample(1, -2); ) )
Çıktı :
Bunu addTwo () yöntemine iletmeden önce: x = 1, y = -2 Bunu addTwo () yöntemine ilettikten sonra: x = 3, y = 0
Yukarıdaki örnekte, kurucunun içindeki ThisExample()
satıra dikkat edin,
add(this);
Burada bunu add()
argüman olarak ileterek yöntemi çağırıyoruz . Bu anahtar sözcük, sınıfın nesne nesnesine başvuruyu içerdiğinden, add()
yöntem içinde x ve y'nin değerini değiştirebiliriz .