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.
Related
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;
}
}
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 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
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.
I've come across some odd behavior in assignment of final variables. You can assign a final varible in a constructor to initialize it, which makes sense. However you can't do the same in a subclass, even if the final variable is a member of the subclass -
public class FinalTest {
public final String name;
public FinalTest()
{
name = "FinalTest";
}
public static class FinalTestSubclass extends FinalTest {
public FinalTestSubclass()
{
name = "FinalTestSubclass"; //<---- this won't compile, assignment to final variable.
}
}
}
Can someone think of a good reason why this should/would work this way?
Every constructor of a subclass must invoke a constructor of the superclass as its first operation. Every final member variable must be initialized before a constructor completes. A final variable can be assigned only once. Given those rules, it is impossible for a subclass constructor to directly assign a value to a final superclass' member.
Making exceptions would increase complexity and create "gotchas" in exchange for limited additional utility.
A practical solution is to provide a superclass constructor that takes a value to be assigned to the final member. This can be protected or package-private if desired. If the superclass is outside of your control, there's a good chance that allowing derived classes to break its assumptions about the finality of its members would cause other problems.
If you were allowed to assign a value to name in FinalTestSubClass it would mean that the value assigned in FinalTest was not actually the final value.
If your example was valid, then this would mean that name could have different values (based upon which class was instantiated), making the final modifier pretty much redundant.
A better question is, why should the behavior you desire be allowed?
informally, final fields should have been initialized when the constructor is finished.
in your subclass constructor, super() has been called implicitly, the constructor of the super class is finished, the final fields in the super class should not be modified.
you may want this instead:
class A
final String s;
A(String s){ this.s = s; }
A() { this("default"); }
class B extends A
B(){ super("B's default"); }
This is standard behavior in Java
The key word final can by used in multiple way, for class close the possibility to inherite from it, for method to override it, for variable allow to be assigned only once in simply words.
For your case this variable is allready assigned in super class,
what You can do is
public class FinalTest {
public final String name = "FinalTest";
public FinalTest()
{
}
public static class FinalTestSubclass extends FinalTest {
public final String name = "FinalTestSubclass";
public FinalTestSubclass()
{
}
}
}
Read more about final variables
In reply to your comment to matt's answer; you can achieve determining the constant in the subclass by passing it in the constructor:
public class FinalTest {
public final String name;
public FinalTest()
{
this("FinalTest");
}
protected FinalTest(String nameConstant)
{
name = nameConstant;
}
public static class FinalTestSubclass extends FinalTest {
public FinalTestSubclass()
{
super("FinalTestSubclass");
}
}
}