java this keyword - java

I have read that in Java you don't have to explicitly bind the this keyword to object, it is done by interpreter. It is opposite to Javascript where you always have to know the value of this. But where is this in Java is pointing - to class or object ? Or does it vary ?
This question is a part of my attempt to understand basic OO concepts and design patterns so I can apply them to Javascript.
Thank you.

In Java, this always refers to an object and never to a class.

The Java language specification states:
When used as a primary expression, the keyword this denotes a value
that is a reference to the object for which the instance method was
invoked (§15.12), or to the object being constructed.
I.e. it always points to an object, not a class.

in java this is refer Current object
like
public class Employee{
String name,adress;
Employee(){
this.name="employee";
this.address="address";
}
}

this refers to current object.
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.

In java 'this' is a keyword, basically used to refer to the current object. In the following example the setter methods are using 'this' to set the values of name and age of current object.
public class Person {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
Person p = new Person();
p.setName("Rishi");
p.setAge(23);
System.out.println(p.getName() + " is " + p.getAge() + " years old");
}
}

From the official documentation (found here):
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.
What this means is that inside the code of any class, when you write this, you specify the fact that you are referring to the current object.
As a side note, you cannot use this with static fields or methods because they do not belong to any specific object (instance of the class).

this keyword is always used in referencing the object of the current class.
where as this() is used for the current class constructors.
for example:
class circle {
public int radius;
public Circle() {
this.radius = 10; //any default value
}
public Circle(int radius) {
this.radius = radius // here this.radius will set instance variable radius
}
public int areaOfCircle() {
return 3.14*radius*radius;
}
}

Related

What are the differences between this and this() in java

Please confirm me is this keyword refer to its owning class and this() method refers to its owning class constructors.
class Tester {
private String blogName;
public Tester() {
this("stackoverflow");
}
public Tester(String str) {
this.blogName = str;
}
public String getBlogName() {
return blogName;
}
}
It help me to if there are other differences between these.
this is a reference to the object on which behalf the current method was invoked. this(anything) is an invocation of constructor.
this("stackoverflow"); is calling the other constructor in the class (this is called a delegated constructor).
this.blogName= str1; is assigning a reference to whatever str1 is referring to to the field blogName. The this in this instance is redundant but is used to disambiguate a field name to an identically named function parameter.
The first example calls the overloaded constructor in the default constructor. You can call all overloaded constructors this way. It has to be the first line in the constructor, just like calls to super().
The second one shows how the special name this refers to the current instance within the class. It's only required to sort out name duplication:
public class ThisDemo {
private static final String DEFAULT_VALUE = "REQUIRED";
private String value;
public ThisDemo() {
this(DEFAULT_VALUE);
}
publi ThisDemo(String value) {
// Required here because the private member and parameter have same name
this.value = value;
}
public String getValue() {
// Not required here, but I prefer to add it.
return value;
}
}
this is a keyword in Java, it means its current instance of the class.
this("stackoverflow") is calling constructor in the class which will be a overloaded call. You can call any other constructors of the same class this way.

Use of "this" operator in Java

Is there any other use of this keyword other than accessing member variable having the same name as local variable
this.x = x
Is there any other situation where it make sense to use this keyword.
One other use of this keyword is in constructor chaining, for example:
class Person {
private String name;
private int age;
public Person() {
//Invoking another constructor
this("John", 35);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
You can pass the current object as a parameter to another method.
Below points have been taken from Java docs
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
From within a constructor, you can also use the this keyword to call another constructor in the same class.
this represents the current instance inside the instance.
It is useful for:
identifying instance variables from locals (including parameters)
it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads.
refer to the instance.
Some examples of applicable uses (not exhaustive):
class myClass
{
private int myVar;
public myClass() {
this(42); // invoke parameterized constructor of current instance
}
public myClass(int myVar) {
this.myVar = myVar; // disambiguate
}
public void another() {
this.second(); // used "just because"
}
private void second() {
System.out.println("whatever");
}
}
You can reference a field or call a method of an enclosing class
public class Examples {
public class ExamplesInner {
private int x;
public ExamplesInner() {
x = 3; // refers to ExamplesInner.x
Examples.this.x = 3; // refers to Examples.x
}
}
private int x;
}
For full usage, read the java language specification
The keyword this may be used only in the body of an instance method,
instance initializer, or constructor, or in the initializer of an
instance variable of a class. If it appears anywhere else, a
compile-time error occurs.
When used as a primary expression, the keyword this denotes a value
that is a reference to the object for which the instance method was
invoked (§15.12), or to the object being constructed.
The type of this is the class C within which the keyword this occurs.
At run time, the class of the actual object referred to may be the
class C or any subclass of C.
The keyword this is also used in a special explicit constructor
invocation statement, which can appear at the beginning of a
constructor body (§8.8.7).
this keyword can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this keyword
can be used to invoke current class method (implicitly)
this can be
passed as an argument in the method call.
this can be passed as
argument in the constructor call.
this keyword can also be used to
return the current class instance.
find examples from this:
http://javarevisited.blogspot.in/2012/01/this-keyword-java-example-tutorial.html
The this operator is used as reference to currently executing object. It is concerned with objects, and hence cannot be and should not be used with static references, where classes are used instead of objects.
The this operator can be used to invoke the constructor like this()
The this operator also avoids naming ambiguities and can be used to pass the current object as reference to functions
this lets you disambiguate between the private member foo and the parameter foo passed into the constructor: EX
class bar
{
private int foo;
public Foo(int foo)
{
this.foo =foo;
}
}

java inheritance

When I change this code into Member m1 = new Member (); It works perfectly. Why it does not work for Super class reference? Please can someone explain?
public class Family {
String Surname = "Richard";
String Address = "No:10, High Street,Colombo";
}
public class Member extends Family{
String Name;
int age;
public void Details() {
System.out.println("full Name ="+ Name +" "+ Surname);
System.out.println("Age =" +age);
System.out.println("Address =" + Address);
}
public static void main(String[] args) {
Member m1 = new Family ();
m1.Name="Anne";
m1.age=24;
m1.Details();
}
You don't have a super class reference. You are having a subclass reference holding a reference to a super class object, that is simply illegal.
Secondly, you need to defined the method you have in subclass also in super class, if you want to see polymorphism into effect. You can only invoke that method on super class reference, that is also defined in super class.
So, you basically need this: -
Family m1 = new Member();
and then define the details() method(Yes, method name should start with lowercase alphabets), in your Family class.
And now, you will get another compiler error, when you try to access the fields of Member. For that, it's better to use a 2-arg constructor in Member class, and from that constructor, invoke the 2-arg super constructor (you need to do this explicitly), or 0-arg super constructor (this is implicit)
public Member(String name, int age) {
this.name = name;
this.age = age;
}
And use this constructor to create the object. It will implicitly call the 0-arg super constructor to initialize it's fields with their default value. If you want to give them a value, you can use a 4-arg constructor in Member class, passing the 2-parameters for super class fields, and then invoke the super class 2-arg constructor from there.
I think, you should better start with a good tutorial, starting with learning Inheritance in general, the access specifiers, then move ahead with polymorphism.

Difference between "field" and "this.field" in Java

I'd like to better understand what is the difference in referring to a class field by using this.field and field alone as in
this.integerField = 5;
and
integerField = 5;
this keyword refers to the current object.
usually we use this.memberVariable to diffrentiate between the member and local variables
private int x=10;
public void m1(int x) {
sysout(this.x)//would print 10 member variable
sysout(x); //would print 5; local variable
}
public static void main(String..args) {
new classInst().m1(5);
}
Off from the concrete question,
the use of this In Overloaded constructors:
we can use this to call overloaded constructor like below:
public class ABC {
public ABC() {
this("example");to call overloadedconstructor
sysout("no args cons");
}
public ABC(String x){
sysout("one argscons")
}
}
The use of this keywords lets you disambiguate between member variables and locals, such as function parameters:
public MyClass(int integerField) {
this.integerField = integerField;
}
The code snippet above assigns the value of local variable integerField to the member variable of the class with the same name.
Some shops adopt coding standards requiring all member accesses to be qualified with this. This is valid, but unnecessary; in cases where no collision exists, removing this does not change the semantic of your program.
When you are in an instance method, you may need to specify to which scope you refer a variable from. For example :
private int x;
public void method(int x) {
System.out.println("Method x : " + x);
System.out.println("Instance x : " + this.x);
}
While, in this example, you have two x variables, one is a local method variable and one is a class variable. You may distinguish between the two with this to specify it.
Some people always use this before using a class variable. While it is not necessary, it may improve code readability.
As for polymorphism, you may refer to the parent class as super. For example :
class A {
public int getValue() { return 1; }
}
class B extends A {
// override A.getValue()
public int getValue() { return 2; }
// return 1 from A.getValue()
// have we not used super, the method would have returned the same as this.getValue()
public int getParentValue() { return super.getValue(); }
}
Both keywords this and super depend on the scope from where you are using it; it depends on the instance (object) you are working with at run-time.
It's exactly the same. Because you often type this.xyz it's a shortcut that means the same thing if there is a field by that name and there isn't a local variable that shadows it.
Though they look and act the same, there is a difference when the same name is shared between a field and a method argument, e.g.:
private String name;
public void setName(String name){
this.name = name;
}
name is the passed parameter, and this.name is the proper class field.
Notice that typing this.... prompts you a list of all the class fields [and methods] in many IDEs.
From the Java tutorials:
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.
So, when you call a method within a object the call looks like this:
public class MyClass{
private int field;
public MyClass(){
this(10); // Will call the constructor with a int argument
}
public MyClass(int value){
}
//And within a object, the methods look like this
public void myMethod(MyClass this){ //A reference of a object of MyClass
this.field = 10; // The current object field
}
}

Why 'this' is not allowed in static methods?

I know this represents the object invoking the method and static methods are not bound to any object but my question is still you can invoke static method on class object .
Why java has made this thing available and not for this ?
this points to the current instance of the class.
Static methods are associated with a class, not an instance, so there's nothing for this to point to.
Here's an example:
public class Foo {
private String name;
public static void someClassMethod() { System.out.println("associated with a class"); }
public Foo(String n) { this.name = n; }
public String getName() { return this.name; }
public void setName(String n) { this.name = n; }
public void doAnotherThing() {
Foo.someClassMethod(); // This is what is really happening when you call a static method in an non-static method.
}
}
Simple answer: this is not defined outside of a non-static method.
Calling static methods on an instance is a syntactic shorthand, which I don't agree should exist.
From every point of view this always means this object, so giving possibility for meaning this class could lead to multiple bugs
The difference here is between a class and an object. A non-static method is called on an object, while a static method is Called on a class.
You can see a Class as a blueprint, with which Objects are built.
A class House has a static method hasDoor() (which will return true), while an object of the type House can have a method openDoor(). You can't open the door of a blueprint.
One can call House.hasDoor(), but not House.openDoor(). One can call
House h = new House();
h.openDoor();
While you can call h.hasDoor(), this is a bit nasty and should be avoided in most cases

Categories

Resources