Java to: Kje in kako jo uporabiti?

V tem članku bomo s pomočjo primerov spoznali to ključno besedo v Javi, kako in kje jih uporabiti.

to ključno besedo

V Javi se ta ključna beseda uporablja za sklicevanje na trenutni objekt znotraj metode ali konstruktorja. Na primer

 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); ) )

Izhod :

 this reference = Main @ 23fc625e reference reference = Main @ 23fc625e

V zgornjem primeru smo ustvarili objekt z imenom obj razreda Main. Nato natisnemo referenco na objekt obj in thisključno besedo razreda.

Tu lahko vidimo, da je referenca obeh in thisenaka. To pomeni, da to ni nič drugega kot sklicevanje na trenutni objekt.

Uporaba te ključne besede

Ključne thisbesede se pogosto uporabljajo v različnih situacijah .

Uporaba tega za imena spremenljivk dvoumnosti

V Javi ni dovoljeno prijaviti dveh ali več spremenljivk z istim imenom znotraj obsega (obseg razreda ali obseg metode). Vendar pa imajo lahko spremenljivke in parametri primerka isto ime. Na primer

 class MyClass ( // instance variable int age; // parameter MyClass(int age)( age = age; ) )

V zgornjem programu imata spremenljivka primerka in parameter isto ime: starost. Tu je prevajalnik Java zmeden zaradi nejasnosti imena.

V takem primeru uporabimo to ključno besedo. Na primer

Najprej si oglejmo primer brez uporabe thisključne besede:

 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); ) )

Izhod :

 mc.age = 0

V zgornjem primeru smo 8konstruktorju podali vrednost kot vrednost. Vendar pa smo dobili 0kot rezultat. Razlog za to je, da se prevajalnik Java zmede zaradi dvoumnosti imen med spremenljivko in parametrom primerka.

Zdaj pa napišite zgornjo kodo s thisključno besedo.

 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); ) )

Izhod :

 obj.age = 8

Zdaj dobimo pričakovani izhod. To je zato, ker ko je konstruktor poklican, se thisznotraj konstruktorja nadomesti s predmetom obj, ki je poklical konstruktor. Zato je starostni spremenljivki dodeljena vrednost 8.

Če je ime parametra in spremenljivke primerka drugačno, prevajalnik samodejno doda to ključno besedo. Na primer koda:

 class Main ( int age; Main(int i) ( age = i; ) )

je enakovredno:

 class Main ( int age; Main(int i) ( this.age = i; ) )

to z Getters in Setters

Druga pogosta uporaba thisključne besede je v nastavitvah in metodah pridobivanja razreda. Na primer:

 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()); ) )

Izhod :

 obj.name: Toshiba

Tu smo uporabili thisključno besedo:

  • za dodelitev vrednosti znotraj metode nastavitve
  • za dostop do vrednosti znotraj getter metode

Uporaba tega v Constructor Overloading

Med delom s preobremenitvijo konstruktorja bomo morda morali priklicati enega konstruktorja iz drugega konstruktorja. V takem primeru konstruktorja ne moremo izrecno poklicati. Namesto tega moramo uporabiti thisključno besedo.

Tu uporabljamo drugačno obliko te ključne besede. Se pravi this(),. Vzemimo primer,

 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); ) )

Izhod :

 2 + 3i 3 + 3i 0 + 0i

V zgornjem primeru smo uporabili thisključno besedo,

  • da pokličete konstruktor Complex(int i, int j)iz konstruktorjaComplex(int i)
  • da pokličete konstruktor Complex(int i)iz konstruktorjaComplex()

Opazite vrstico,

 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); ) )

Izhod :

 Pred predajo metode addTwo (): x = 1, y = -2 Po predaji metode addTwo (): x = 3, y = 0

V zgornjem primeru znotraj konstruktorja ThisExample()opazite vrstico,

 add(this);

Tu pokličemo add()metodo tako, da jo posredujemo kot argument. Ker ta ključna beseda vsebuje sklic na objekt obj razreda, lahko znotraj add()metode spremenimo vrednost x in y .

Zanimive Članki...