This command in java

Java this Keyword

In the above program, the instance variable and the parameter have the same name: age. Here, the Java compiler is confused due to name ambiguity.

In such a situation, we use this keyword. For example,

First, let’s see an example without using this keyword:

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 java-exec">class Main < int age; Main(int age)< this.age = age; >public static void main(String[] args) 

Now, we are getting the expected output. It is because when the constructor is called, this inside the constructor is replaced by the object obj that has called the constructor. Hence the age variable is assigned value 8.

Also, if the name of the parameter and instance variable is different, the compiler automatically appends this keyword. For example, the code:

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

this with Getters and Setters

Another common use of this keyword is in setters and getters methods of a class. For example:

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

Here, we have used this keyword:

Using this in Constructor Overloading

While working with constructor overloading, we might have to invoke one constructor from another constructor. In such a case, we cannot call the constructor explicitly. Instead, we have to use this keyword.

Here, we use a different form of this keyword. That is, this() . Let's take an example,

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

In the above example, we have used this keyword,

  • to call the constructor Complex(int i, int j) from the constructor Complex(int i)
  • to call the constructor Complex(int i) from the constructor Complex()

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,

Table of Contents

Источник

Using the this Keyword

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .

Using this with a Field

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

For example, the Point class was written like this

but it could have been written like this:

Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x , the constructor must use this.x .

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.

public class Rectangle < private int x, y; private int width, height; public Rectangle() < this(0, 0, 1, 1); > public Rectangle(int width, int height) < this(0, 0, width, height); > public Rectangle(int x, int y, int width, int height) < this.x = x; this.y = y; this.width = width; this.height = height; >. >

This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor creates a 1x1 Rectangle at coordinates 0,0. The two-argument constructor calls the four-argument constructor, passing in the width and height but always using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number and the type of arguments.

If present, the invocation of another constructor must be the first line in the constructor.

Источник

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.

Источник

Читайте также:  Python random int in range
Оцените статью