Java method invoke this

Using «this» with methods (in Java)

what about using «this» with methods in Java? Is it optional or there are situations when one needs to use it obligatory? The only situation I have encountered is when in the class you invoke a method within a method. But it is optional. Here is a silly example just to show what I mean:

public class Test < String s; private String hey() < return s; >public String getS() < String sm = this.hey(); // here I could just write hey(); without this return sm; >> 

Um, I suggested closing based on stackoverflow.com/questions/516291/the-use-of-this-in-java but I no longer think they’re close enough.

I have understood what «this» mean -a single «this» can be used if you want to refer to the whole current instance of the object, or any element of the object, i.e this.instanceVar.But sometimes you need to use «this» — in the constructor, if the argument is the same: this.var = var.But for methods?

I’ve updated my answer to show where it might be necessary in a method too, for exactly the same reason. Changing parameter names removes the need for this, however.

7 Answers 7

Three obvious situations where you need it:

  • Calling another constructor in the same class as the first part of your constructor
  • Differentiating between a local variable and an instance variable (whether in the constructor or any other method)
  • Passing a reference to the current object to another method

Here’s an example of all three:

public class Test < int x; public Test(int x) < this.x = x; >public Test() < this(10); >public void foo() < Helper.doSomethingWith(this); >public void setX(int x) < this.x = x; >> 

I believe there are also some weird situations using inner classes where you need super.this.x but they should be avoided as hugely obscure, IMO 🙂

Читайте также:  Java apply method to list

EDIT: I can’t think of any examples why you’d want it for a straight this.foo() method call.

EDIT: saua contributed this on the matter of obscure inner class examples:

I think the obscure case is: OuterClass.this.foo() when accessing foo() of the outer class from the code in an Inner class that has a foo() method as well.

A newer use case is to create a method reference using this instance, e.g., Runnable r = this::foo; .

I use «this» to clarify code, often as a hint that I’m calling an instance method rather than accessing a class-level method or a field.

But no. Unless disambiguation is required due to scope naming collision, you don’t actually need «this.»

It’s a hint—a coding construct given additional meaning by consistent or standardized use under more constrained circumstances than are legal.

But «this» will work for static methods, instance methods, and super’s methods, so unless someone knows your specific hint rules, it’s absolutely unless. Actually it makes your code even harder to understand.

For most general programing, the this keyword is optional and generally used to avoid confusion. However, there are a few places where it is needed.

class Foo < int val; public Foo(int val) < this(val, 0); //this MUST be here to refer to another constructor >public Foo(int val, int another) < val = val; //this will work, but it generally not recommended. this.val = val; //both are the same, but this is more useful. method1(); //in a Foo instance, it will refer to this.method1() this.method1(); //but in a Foo2 instance, you must use this to do the same >public void method1() <> > class Foo2 extends Foo < public Foo2(int val) < this(val); //this will refer to the other Foo2 constructor >public Foo2(int val, int another) < super(val, another); super.method1(); //this will refer to Foo.method1() >@Override public void method1() <>//overridden method > 

These are not all the cases, but some of the more general ones. I hope this helps you better understand the this and super keywords and how/when to use them.

Btw, as other people commented above, having val = val; in the constructor in this example, will not give the desired effect. The program compiles, but the instance variable will never be initialised in the constructor. It will always be 0 — from the default constructor.

The only reason to prepend this in front of a method invocation is to indicate that you’re calling a non-static method. I can’t think of any other valid reason to do this (correct me I’m wrong). I don’t recommend this convention as it doesn’t add much value. If not applied consistently then it could be misleading (as a this-less method invocation could still be a non-static method). How often does one care if the method being invoked is static or not? Furthermore, most IDEs will highlight static methods differently.

I have heard of conventions where this indicates calling the subclass’s method while an absence of this is calling the super class’s method. But this is just silly as the convention could be the other way around.

Edit: As mmyers points out (see comment), this works with static methods. With that, I see absolutely no reason to prepend with this as it doesn’t make any difference.

this works with static methods, but it produces a warning (at least with my settings). So it could be useful, but it’s too much boilerplate for something syntax highlighting gives you anyway.

The only time it is really required is when you have a parameter to a method with the same name as a member variable. Personally, I try to always use it to make the scope of the variable/method explicit. For example you could have a static method or an instance method. When reading the code it can be helpful to know which is which.

I meant to disambiguate between a parameter and a member variable and a static and an instance method, not be between variables and methods.

Not an answer (so feel free to vote it down), but I couldn’t fit this into a comment where someone was asking.

A lot of people use «this.x» to visually differentiate instance variables from local variables and parameters.

private int sum; public int storeSquare (int b) < int c=b*b; this.sum+=c; // Makes sum "pop" I guess return c; >

Personally I think it’s a bad habit: any usable editor will put instance and local variables in a different color for you reliably—it doesn’t require any human-fallible patterns.

Doing it with «this.» is only 50% safe. Sure the compiler will catch it if you try to put this.x when x is a local variable, but there is nothing that is going to stop you from «Forgetting» to tag an instance variable with this., and if you forget to tag just one (or if someone else works on your code) and you are relying on the pattern, then the pattern may be more damaging than good

Personally I’m fairly sure the pattern stems from programmers (rightful) discomfort with the fact that in this case:

the fact that you need «this.» in front of the me is determined by the name of the parameter—I agree it just feels sloppy. You want to be consistent—if you need this. in front of the me there, why not always use it?

Although I understand the discomfort, typing this. every single place that an instance variable is used is just pedantic, pointless, ugly and unreliable. If it really bothers you and you absolutely need to use a pattern to solve it, try the habit of putting «p» in front of your parameters. As a side effect, it should even make it more constant because the parameter case will now match the method case..

public void setMe( int pMe) 

Источник

Using the keyword «this» in java [duplicate]

I’m trying to get an understanding of what the the java keyword this actually does. I’ve been reading Sun’s documentation but I’m still fuzzy on what this actually does.

12 Answers 12

The this keyword is a reference to the current object.

Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self .

If you were to reference objects that are intrinsically yours you would say something like this:

Think of this as just a way for a type to say «my». So a psuedocode representation would look like this:

You could do the above without «this», for example using something like hungarian notation. m_bar = bar. So does not really explain what this is really important for.

@ng: What do you do when you can’t rename the field? Like when it’s a protected field from a super class?

@ng — You are correct that my usage of «this» could easily be replaced with careful naming conventions. However I believe that I gave the most simple example as it seems clear that the OP is just learning OOP and may have trouble understanding a more advanced usage of «this».

True, but over simplifying the example can be confusing also, making use of «this» to pass the actual object outside the scope of the object itself provides a very clear example of its application and importance.

The keyword this can mean different things in different contexts, that’s probably the source of your confusion.

It can be used as a object reference which refers to the instance the current method was called on: return this;

It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:

It can be used to invoke a different constructor of a a class from within a constructor:

It can be used to access enclosing instances from within a nested class:

1#Does «this» only used and written through constructor? 2# what about this.setTittle(«Tittle of Fram») ; as you can see it is used to invoke method but I didn’t understand its semantic ??

@user2019510: no, it is not only used in constructors; my answer contains examples for different uses. And yes, it’s used to invoke methods, in that case it means the current object, and works just like using any other object reference to invoke a method.

«this» is a reference to the current object.

The keyword this is a reference to the current object. It’s best explained with the following piece of code:

public class MyClass < public void testingThis() < // You can access the stuff below by // using this (although this is not mandatory) System.out.println(this.myInt); System.out.println(this.myStringMethod()); // Will print out: // 100 // Hello World >int myInt = 100; string myStringMethod() < return "Hello World"; >> 

It’s not used a lot unless you have code standard at your place telling you to use the this keyword. There is one common use for it, and that’s if you follow a code convention where you have parameter names that are the same as your class attributes:

public class ProperExample < private int numberOfExamples; public ProperExample(int numberOfExamples) < this.numberOfExamples = numberOfExamples; >> 

One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):

public class Square < public Square() < this(0, 0); >public Square(int x_and_y) < this(x_and_y, x_and_y); >public Square(int x, int y) < // finally do something with x and y >> 

This keyword works the same way in e.g. C#.

No it doesn’t. main() is a static method and so there is no ‘this’ pointer because there is no object that is invoking it. This should not compile.

This is another poor example of how «this» can be used, and why its fundamentally important to the OO paradigm.

An even better use of this

public class Blah implements Foo < public Foo getFoo() < return this; >> 

It allows you to specifically «this» object in the current context. Another example:

How else could you do these operations.

For your first example: it really makes no sense to return ‘this’ from an object. The caller already has a reference to your object, how else would he invoke the method?

@eljenso: If «return this;» is the only line in the method, then yes, it’s pretty useless. But if it’s e.g. a setter, it allows you to do method chaining: myFoo.setBar(myBar).setBaz(myBaz).setMyInt(1);

Not only that but what if returning this is a characteristic of an interface implementation? I challenge you to show me a single complex project that does not need to return this at some point. Its a critical requirement of most OO systems.

@ng Every caller invokes getFoo() on a (sub)type of Foo. Why the method if you can do Blah blah = new Blah(); Foo foo = blah; Maybe we can turn things around, and you can show me a project where «this» is returned as you described, so I can better understand what you’re trying to say.

«this» keyword refers to current object due to which the method is under execution. It is also used to avoid ambiguity between local variable passed as a argument in a method and instance variable whenever instance variable and local variable has a same name.

public class ThisDemo1 < public static void main(String[] args) < A a1=new A(4,5); >> class A < int num1; int num2; A(int num1) < this.num1=num1; //here "this" refers to instance variable num1. //"this" avoids ambigutiy between local variable "num1" & instance variable "num1" System.out.println("num1 :: "+(this.num1)); >A(int num, int num2) < this(num); //here "this" calls 1 argument constructor within the same class. this.num2=num2; System.out.println("num2 :: "+(this.num2)); //Above line prints value of the instance variable num2. >> 

The keyword ‘this‘ refers to the current object’s context. In many cases (as Andrew points out), you’ll use an explicit this to make it clear that you’re referring to the current object.

*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say «System.out.println(this);». Or you could assign the value of this to another variable in an assignment statement.

In fact, you can do anything with this that you could do with any other variable, except change its value.*

That site also refers to the related concept of ‘super‘, which may prove to be helpful in understanding how these work with inheritance.

Источник

Оцените статью