Pages

Sunday, January 22, 2017

Constructors and this keyword

  1. Constructors are the special methods whose name is same as Class name.
  2. Constructors do not have return type.
  3. Constructors are invoked by the JVM automatically at the time of object creation.
  4. Constructors are mainly used to initialize instance variables of class with different set of values.
Example 1:

class Lab7{
    public static void main(String args[]){
        
        Student st1 = new Student();
        st1.show();
        Student st2 = new Student(11, "Bangalore");
        st2.show();
        Student st3 = new Student(22, "Bangalore", "Bangalore@xxx.com");        st3.show();
        Student st4 = new Student(33, "Bangalore", "Bangalore@ggg.com", 5656565);        st4.show();
        
        
    }
}

class Student{
    int sid;
    String sname;
    String email;
    long phone;
    
    Student(){
        System.out.println("Student default constructor");
    }
    
    Student(int id, String sn){
        System.out.println("Student 2-Arg Default Constructor");
        sid = id;
        sname = sn;
    }
    
    Student(int id, String sn, String em){
        System.out.println("Student 3-Arg Default Constructor");
        sid = id;
        sname = sn;
        email = em;
    }
    
    Student(int id, String sn, String em, long ph){
        System.out.println("Student 4-Arg Default Constructor");
        sid = id;
        sname = sn;
        email = em;
        phone = ph;
    }
    
    void show(){
        System.out.println(sid+"\t"+sname+"\t"+email+"\t"+phone);
    }
} 

Example 2:

class Lab14{
    public static void main(String args[]){
    
        Student st1 = new Student(-11);
        st1.show();     
    }
}

class Student{
    int age = 18;
    
    Student(int ag){
        System.out.println("Student 1-Arg Default Constructor");
        if(age<18){
            return;
        }
        age = ag;
    }
        
    void show(){
        System.out.println(age);
    }
} 


/*
empty return statements are allowed in Constructors as they do not provide a return type.
*/

this keyword

  1. this is a keyword which acts as a reference variable.
  2. this reference variable contains address of current object.
  3. this is an instance reference variable and cannot be accessed from static context.
  4. this keyword can be used in three ways:
    • To access the variable
      Syntax:
          this.<variableName>
      Ex:
          this.a;
          this.b;
      
    • To access the methods:
      Syntax:
          this.<methodName>();
      Ex:
          this.m1();
          this.m2();
      
    • To access the overloaded constructor:
      Syntax:
          this(params);
          
      Ex:
          this();     //-> invokes Default constructor
          this(99);   //-> invokes 1-Arg constructor
          this(99,88) //-> invokes 2-Arg constructor
      

  5. this is a final variable. It cannot be modified.
    Ex:
        this = null;
        this = new <ClassName>;
    //this is not allowed
    

Example 1:

In the below example, the arguments are assigned to itself inside the Constructor, therefore the output value is default values


class Lab5{
    public static void main(String args[]){
        Student st1 = new Student(1, "Bangalore");
        st1.show();
        
        Student st2 = new Student(2, "Karnataka");
        st2.show();
    }
}

class Student{
    int sid;
    String sname;
    
    Student(int sid, String sname){
        System.out.println("Student 2-arg constructor");
        sid=sid;
        sname=sname;
    }
    void show(){
        System.out.println(sid+"\t"+sname);
    }
}

/*

Output:
Student 2-arg constructor
0 null
0 null
*/

Example 2:

class Lab6{
    public static void main(String args[]){
        Student st1 = new Student(11, "Bangalore");
        st1.show();
        
        Student st2 = new Student(22, "Karnataka");
        st2.show();
    }
}

class Student{
    int sid;
    String sname;
    
    Student(int sid, String sname){
        System.out.println("Student 2-arg constructor");
        this.sid=sid;
        this.sname=sname;
    }
    void show(){
        System.out.println(sid+"\t"+sname);
    }
}

/*

Output:
Student 2-arg constructor
11  Bangalore
22 Karnataka
*/

Example 3:

class Lab12{
    public static void main(String args[]){
        Student st1 = new Student(11, "Bangalore", "Bangalore@GGG.com", 4566545);
        st1.show();
    }
}

class Student{
    int sid;
    String name;
    String email;
    long phone;
    
    Student(){
        System.out.println("Student DC");
    }
    
    Student(int sid){
        this.sid = sid;
        System.out.println("Student 1-arg");
    }
    
    Student(int sid, String name){
        this.sid = sid;
        this.name = name;
        System.out.println("Student 2-arg");
    }
    
    Student(int sid, String name, String email){
        this.sid = sid;
        this.name = name;
        this.email = email;
        System.out.println("Student 3-arg");
    }
    
    Student(int sid, String name, String email, long phone){
        this.sid = sid;
        this.name = name;
        this.email = email;
        this.phone = phone;
        System.out.println("Student 4-arg");
    }
    
    void show(){
        System.out.println(sid+"\t"+name+"\t"+email+"\t"+phone);
    }
}

/*output:
Student 4-arg
11      Bangalore     Bangalore@GGG.com     4566545
*/

Example 4:

class Lab13{
    public static void main(String args[]){
        Student st1 = new Student(11, "Bangalore", "Bangalore@GGG.com", 4566545);
        st1.show();
    }
}

class Student{
    int sid;
    String name;
    String email;
    long phone;
    
    Student(){
        System.out.println("Student DC");
    }
    
    Student(int sid){
        this();
        this.sid = sid;
        System.out.println("Student 1-arg");
    }
    
    Student(int sid, String name){
        this(sid);
        this.name = name;
        System.out.println("Student 2-arg");
    }
    
    Student(int sid, String name, String email){
        this(sid, name);
        this.email = email;
        System.out.println("Student 3-arg");
    }
    
    Student(int sid, String name, String email, long phone){
        this(sid, name, email);
        this.phone = phone;
        System.out.println("Student 4-arg");
    }
    
    void show(){
        System.out.println(sid+"\t"+name+"\t"+email+"\t"+phone);
    }
}


/*output:
Student DC
Student 1-arg
Student 2-arg
Student 3-arg
Student 4-arg
11      Bangalore     Bangalore@GGG.com     4566545
*/

Example 5:

Recursive constructor invocation
class Lab14{
    public static void main(String args[]){
        Hello h1 = new Hello();
    }
}

class Hello{
    Hello(){
        this();
    }
}

/*
Lab14.java:8: error: recursive constructor invocation
        Hello(){
        ^
1 error
*/

Example 6:

Recursive constructor invocation:
class Lab15{
    public static void main(String args[]){
        Hello h1 = new Hello();
    }
}

class Hello{
    Hello(){
        this(10);
    }
    
    Hello(int i){
        this();
    }
}

/*

C.T.E
Lab15.java:12: error: recursive constructor invocation
        Hello(int i){
        ^
1 error
*/

Example 7:

this is final and it cannot be changed.
class Lab20{
    public static void main(String args[]){
        Hello h = new Hello();
        //h.show();
    }
}

class Hello{
    void show(){
        this = null;
        this=new Hello();
    }
}


/*

Lab20.java:10: error: cannot assign a value to final variable this
                this = null;
                this = new Hello();
                ^
2 errors
*/

Example 8:

Assigning Incompatible reference variables using this.
class Lab22{
    public static void main(String args[]){
        new Hello().show();
        new Hai().show();
        
    }
}

class Hello{
    void show(){
        Hello h1 = this;
        Hai h2 = this;
    }
}

class Hai{
    void show(){
        Hello h1 = this;
        Hai h2 = this;
    }
}

/*
C.T.E

F:\JLC Programs\OOPS\this keyword\src>javac -d ..\classes Lab22.java
Lab22.java:12: error: incompatible types: Hello cannot be converted to Hai
                Hai h2 = this;
                         ^
Lab22.java:18: error: incompatible types: Hai cannot be converted to Hello
                Hello h1 = this;
                           ^
2 errors
*/

Example 9:

this can be used with class name also
class Lab23{
    public static void main(String args[]){
        Hello h = new Hello();
        h.show();
    }
}

class Hello{
    int a;
    void show(){
        String a = "Bangalore";
        System.out.println(a);
        System.out.println(this.a);
        System.out.println(Hello.this.a);
    }
}

/*
Output:
Bangalore
0
0
*/


Summary : Constructors

  1. Constructor without any arguments is called Default Constructor.
  2. When you are not writing any constructor inside the class then one default constructor will be inserted by the Java Compiler.
  3. When you are writing any constructor inside the class then default constructor will not be inserted by the Java Compiler.
  4. You can write multiple constructors inside the class by changing parameters. This process is called as CONSTRUCTOR OVERLOADING.
  5. When you are overloading constructors then parameters must differ in terms of:
    • Number of parameters
    • Type of parameters
    • Order of parameters

    class Hello{
        int a;
        String str;
        Hello(int a, String str){...} //VALID
        Hello(int a, String str){...} //INVALID
        Hello(int a, int b){...} //VALID
        Hello(String str, int a){...} //VALID
    }
    
    
  6. You cannot invoke the constructor. Always JVM invokes automatically.
  7. You cannot specify the return type for the constructor. When you specify the return type for the constructor then it will be treated as normal method.
  8. You can use empty return statement inside the Constructor.

Summary :this keyword

  1. You can use the same name for local variables and instance variables.
  2. When you access any variable directly then the following things will happen:
    1. Checks whether that variable is declared in the local scope or not.
    2. If found in the local scope, that local variable will be used.
    3. If not found in the local scope, then checks whether that variable is declared in the class scope or not.
    4. If found, that class level variable will be used.
  3. When you have same name for local variables and class level variables then do the following:
    • Refer the local variable directly.
    • Refer the class level variable using this keyword.
  4. call to constructor using this must be from constructor only, not from methods and blocks.
    class Hello{
        Hello(){}
    
        Hello(int a){
            this(); //VALID
        }
    
        {
            this();//INVALID
        }
    
        void show(){
            this();//INVALID
        }
    }
    
    
  5. call to this must be first statement in the Constructor.
  6. The process of invoking one constructor from another constructor using this is called as CONSTRUCTOR CHAINING.
  7. this is an instance variable and cannot be referenced from static context.
  8. Local variables cannot be referred using this keyword.
  9. this is a final reference variable and cannot be modified.
    1. this = null; //INVALID
    2. this = new Hello(); //INVALID9
  10. this can be assigned to current class reference variable
    class Hello{
        void show(){
            Hello h1 = this; //VALID
            Hai h2 = this; //INVALID
        }
    }
    
    
    class Hai{
        void show(){
            Hello h1 = this; //INVALID
            Hai h2 = this; //VALID
        }
    }
    
    
  11. this keyword can be referred with current class name.
    class Hello{
        int a;
        void show(){
            System.out.println(Hello.this.a); //VALID
            System.out.println(Hai.this.a); //VALID
        }
    }
    
    

No comments:

Post a Comment