Saturday, November 22, 2014

Day8 (Java Tutorial)...topis- this keyword, this() operator

Please continue after from here-
http://selenium-makeiteasy.blogspot.in/2014/11/day7-java-tutorialtopis-constructors.html

*How to initialize or refer non-static members or instance members without creating object ?

Ans-
by using 'this' keyword.

*The Keyword 'this' is used to refer the current class members (global variable and methods). 'this' keyword can be used in constructor as well as non-static methods.

ex-
public class Demo {
    int a;
    Demo(int a){
        this.a = a;
    }
    public static void main(String[] args) {
        System.out.println("program starts");
        Demo ref = new Demo(10);
        System.out.println("value of a-> "+ref.a);
       
        System.out.println("Program ends.");
    }
}

output
---------
program starts
value of a-> 10
Program ends.



this() operator-
-------------------
  • A constructor of a class can invoke another constructor of the same class using 'this()' operator.
  • Recursive constructor invocation is not possible using "this()" operator.
  • Inside a constructor "this()" statement should be always the 1st statement inside the constructor body.
 ex-

public class Demo {
    Demo(){
        this(10);//this statement should always be 1st statement inside constructor.
        //this will call the Demo(int a) constructor
        System.out.println("default constructor.");
    }
    Demo(int a){
        System.out.println("this is called from default constructor.");
    }
    public static void main(String[] args) {
        System.out.println("program starts");
        Demo ref = new Demo();//this will call default constructor
        System.out.println("Program ends.");
    }
} 

output
 program starts
this is called from default constructor.
default constructor.
Program ends.

No comments:

Post a Comment