Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

The this keyword

java



+ Font mai mare | - Font mai mic



The this keyword

If you have two objects of the same type called a and b, you might wonder how it is that you can call a method f( ) for both those objects:



class Banana }

Banana a = new Banana(), b = new Banana();

a.f(1);

b.f(2);

If there's only one method called f( ), how can that method know whether it's being called for the object a or b?

To allow you to write the code in a convenient object-oriented syntax in which you "send a message to an object," the compiler does some undercover work for you. There's a secret first argument passed to the method f( ), and that argument is the handle to the object that's being manipulated. So the two method calls above become something like:

Banana.f(a,1);

Banana.f(b,2);

This is internal and you can't write these expressions and get the compiler to accept them, but it gives you an idea of what's happening.

Suppose you're inside a method and you'd like to get the handle to the current object. Since that handle is passed secretly by the compiler, there's no identifier for it. However, for this purpose there's a keyword: this. The this keyword - which can be used only inside a method - produces the handle to the object the method has been called for. You can treat this handle just like any other object handle. Keep in mind that if you're calling a method of your class from within another method of your class, you don't need to use this; you simply call the method. The current this handle is automatically used for the other method. Thus you can say:

class Apricot

void pit()

Inside pit( ), you could say this.pick( ) but there's no need to. The compiler does it for you automatically. The this keyword is used only for those special cases in which you need to explicitly use the handle to the current object. For example, it's often used in return statements when you want to return the handle to the current object:

//: Leaf.java

// Simple use of the 'this' keyword

public class Leaf

void print()

public static void main(String[] args)

Because increment( ) returns the handle to the current object via the this keyword, multiple operations can easily be performed on the same object.



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 695
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved