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;
}
}
Related
I have the following code for my class, with one parameter:
public class StudentChart {
public StudentChart(int[] Results) {
int[] results = Results;
}
How can I use results elsewhere in the class? I had assumed that variables and arrays declared in the constructor were global, but apparently not.
Also, what is the purpose of using the constructor to store data if it's not global?
You should check out some articles on scope in Java.
Instance Variables
Variables defined within in a class itself and not in a constructor or method of the class.They are known as instance variables because every instance of the class (object) contains a copy of these variables. The scope of instance variables is determined by the access specifier that is applied to these variables.
public class StudentChart{
//instance variable private is the "access modifier" you can make it public, private protected etc.
private int[] results;
Argument Variables
These are the variables that are defined in the header of constructor or a method. The scope of these variables is the method or constructor in which they are defined. The lifetime is limited to the time for which the method keeps executing. Once the method finishes execution, these variables are destroyed.
public int foo(int argumentVariable)
public class Foo{
public Foo(int constructorVariableArgument)
constructorVariable = constructorVariableArgument
}
Local Variables
A local variable is the one that is declared within a method or a constructor (not in the header). The scope and lifetime are limited to the method itself.
public void foo(){
int methodVariable = 0;
}
Loop Variables
Loop variables are only accessible inside of the loop body
while(condition){
String foo = "Bar";
.....
}
//foo cannot be accessed outside of loop body.
Make it a class variable. This way, when you call the constructor, you will fill the results array and can use it elsewhere in your class. You'll also want this class variable to be private.
public class StudentChart {
private int[] results;
public StudentChart(int[] Results) {
results = Results;
}
}
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.
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
}
}
I have this inheritance structure:
public abstract class Mom {
int dummy;
Mom() {
dummy = 0;
}
Mom(int d) {
this();
dummy = d;
}
}
public class Kid extends Mom {
String foo;
Kid() {
super();
foo = "";
}
Kid(int d) {
super(d);
}
}
// ...
Kid kiddo = new Kid(10);
// kiddo.foo == null !
My argument-less constructor of Kid is never called! Here's what I expected:
new Kid(10) → Kid#Kid(int)
super(d) → Mom#Mom(int)
this() → Kid#Kid() // doh!!
super() → Mom#Mom()
Is it possible, from Mom, to call Kid's argument-less constructor?
I guess it's not, and I'll add an abstract method[1] init() that Mom will call and that Kids will have to override.
But I just wanted to know the exact reason, and if possible, examples proving why wanting to call subclass' constructor is a bad idea (even if the subclass' constructor does call super()).
// in Mom:
protected abstract void init();
public Mom() {
dummy = 0;
init();
}
// in Kid:
#Override
protected abstract void init() {
foo = "";
}
The way I would arrange these so you don't need to call every constructor.
public abstract class Parent {
final int dummy;
Parent () {
this(0);
}
Parent (int d) {
dummy = d;
}
}
public class Kid extends Parent {
final String foo = "";
Kid() {
}
Kid(int d) {
super(d);
}
}
Using final ensures that every fields is set once.
Its considered bad practice to call any override-able method from a constructor, so making constructors override-able which be a bad idea.
this() calls the constructor of the same class because constructors don't follow inheritance (nor do static methods)
new Kid(10) --> Kid#Kid(int)
super(d) --> Mom#Mom(int)
this() --> Mom#Mom()
Constructors do this otherwise you are in danger for calling the same constructor more than once and there is no way to guarantee that final methods are set only once.
From the JLS §8.8.7.1 (emphasis by me):
Alternate constructor invocations begin with the keyword this (possibly prefaced with explicit type arguments). They are used to
invoke an alternate constructor of the same class.
Superclass constructor invocations begin with either the keyword super (possibly prefaced with explicit type arguments) or a Primary
expression. They are used to invoke a constructor of the direct
superclass.
So, a this-constructor-invocation always refers to the same class, never to a child class.
While it is possible to invoke virtual methods in a constructor, it is unsafe and considered bad practice as it may result in those methods working with partly initialized object instances.
For your problem, there are several possible solutions:
Initialize the member foo at declaration, i.e. foo = "";. This is also known as field initializers
Use an instance initializer: { foo = ""; }. Note that you can have more than one instance initializer if needed in your class.
Bite the bullet and repeat the initialization in all constructors
According to JLS §12.5, initialization in (1) and (2) is always executed before constructors themselves are called, so you have a well-defined object initialization without the need of resorting to problematic patterns.
If a member is initialized multiple times, then the last initialization wins:
4) Execute the instance initializers and instance variable initializers
for this class, assigning the values of instance variable initializers
to the corresponding instance variables, in the left-to-right order in
which they appear textually in the source code for the class.
If the same field is initialized in a constructor as well, then the constructor wins.
You should have these constructors for the Kid class:
Kid(int i) {
super(i);
whatever();
}
Kid () {
this( DEFAULT_VALUE);
}
so that all call to parent constructor are made via fully qualified constructor of child class. And have a default behavior for all constructor of your class that is not bypassed as it is the case with your current code.
I encountered a code where this() method in java takes three parameters two being integers and the third one is boolean value.
what exactly does that mean ? Are there any other variants of this() method ?
Hera is the actual code.
public SegmentConstructor(int seqNum_, int length_) {
this(seqNum_, length_, false);
}
Thank You..
It means that there is another constructor in the current class that has that signature.
public SegmentConstructor(int seqNum_, int length_) {
this(seqNum_, length_, false); // calls the constructor below.
}
public SegmentConstructor(int seqNum_, int length_, boolean required_) {
seqNum = seqNum_;
length = length_;
required = required_;
}
The this method is just a way to call one of your class's constructors from within another constructor, to help avoid code duplication. It can only be called on the first line of a constructor--never from within any other method.
this simply invokes another constructor to run. So, look for other constructors with that signature.
As said before this invokes another constructor, mostly as a convenience method.
Trivial example:
class A {
private int value;
public A(int val) {
value = val;
}
public A() {
this(0); //0 as default
}
}
Normally you do use calls to this() when the most specific constructor (that one with the most parameters) is not just assignment but contains more logic that you don't want to repeat/copy etc.
Just because it fits in here: super() can have parameters, too, i.e. this calls a super class' constructor with parameters from the sub class' constructor.
It is a constructor call. If your class implements different constructors with a differing number of arguments, you can chain your constructors like this:
class A {
public A(boolean arg) {
...
}
public A() {
this(false); // invokes the constructor with the boolean argument
}
}
Sometimes it makes sense to create a private constructor taking different arguments and provide public and/or protected constructors with other/fewer arguments and delegate object construction to that private constructor.
It is important to know that no other code may be placed before the call to this(...). However, after calling this(...), you can do everything you could in any other constructor.
Edit: Since this(...) calls a constructor, it can only be called from within other constructors (belonging to the same class).
class MyClass
{
private int var1;
private int var2;
private boolean flag;
public MyClass(int var1_,int var2_)
{
this(var1_,var2_,false);
}
public MyClass(int var1_,int var2_,boolean flag_)
{
var1 = var1_;
var2 = var2_;
flag = flag_;
}
public String toString()
{
return (new Boolean(flag).toString());
}
public static void main(String[] args)
{
MyClass my = new MyClass(5,6);
System.out.println(my);
}
}
So it works.
this() is not a method but is a reserved keyword pointing to a overloaded constructor of the same class.
The number of parameters you pass should point to an existing corresponding constructor defined in the class.
The super() also has the semantics however the constructor is defined in one of its parent hierarchy.