Friday, August 2, 2024

this and Constrcutors Part-2

 

This :

·        ‘This ‘ is predefined k/w in java.

·        ‘This’ k/w can be used to refer current class instance variable

·        ‘this’ k/w can be used to refer current class instance Method

·        ‘this ’ k/w can be used to refer current class instance constructor

                             

without this k/w:

package OOPSBasics;

public class Student4

{

               String name; // instance variables

               String address;

               // DEF consstr

               Student4()

               {

                  //   not compulsory to write any stmts here      

               }

              

               Student4(String name, String address)// 2 Param constr

               { // 

                              System.out.println("calling 2 Param constr");

                              name = name;

                              address = address;          

               }

              

               void display() //  instance method

               {

                              System.out.println("name="+ name + ",address="+ address);

               }

               public static void main(String[] args)

               {

                              Student4 s1 = new Student4("Ram","Bng");

                              s1.display();

               }

}

o/p:

calling 2 Param constr

name=null,address=null

With ‘this’ k/w:

this is used to differentiate the instance variable and local variable.

Ex:

package ConstructorBasics;

public class Student4

{

               String name; // instance variables

               String address;

               // DEF consstr

               Student4()

               {

                             

               }

              

               Student4(String name, String address)// 2 Param constr

               { // 

                              System.out.println("calling 2 Param constr");

                              this.name = name;

                              this.address = address;  

               }

              

               void display() //  instance method

               {

                              System.out.println("name="+ name + ",address="+ address);

               }

               public static void main(String[] args)

               {

                              Student4 s1 = new Student4("Ram","Bng");

                              s1.display();

               }

}

o/p:

calling 2 Param constr

name=Ram,address=Bng

ex1: this is used to refer the current class instance variables i.e name , Address

package OOPSBasics;

public class Student4

{

               // instance variables       

               String  name;

               String address;

               //  can be used to initialise instance var                

               void M1() //   non static method

               {

                              System.out.println("Calling M1()");

                              // 1   refer the current class intance variables i.e name , Address

                              // name = "Ramu";address = "Bng"; using this k/w

                              this.name = "Ramu";

                              this.address ="Bangalore";

                              System.out.println("name="+ name + ", address="+ address);

               }

              

               Student4() //  Def const -   special   method -

               {

                              System.out.println("Def const is called ");

               }             

              

               Student4(String sname, String sAddress) //   2 PC

               {

                              System.out.println(" PC is called");

                             

               }             

              

               public static void main(String[] args)

               {

                              System.out.println("in main");   

                              // can be used  -to refer current class instance var

                              //                                       instance Method

                              //                                      constructor

                                            

                              // use this k/w in  main()

//            this.name ="Ramu";

//            this.address = "Bangalore";        

//                           this.name =  "Ramu";// Cannot use this in a static context

                              //  We cannot use this k/w in static  method

                              //  this k//w cannot be used in static method

                              //     where should we use?

                             

                              // create obj for class Student4

                              Student4 s1 = new Student4();   

                               //   Call Def constr

                              //   Def const is called

                             

                              // caling M1()

                              s1.M1();

                             

                             

               }

}

o/p:

in main

Def const is called

Calling M1()

name=Ramu, address=Bng

Calling current class instance Method using this :

package OOPSBasics;

public class Student4

{

               // instance variables       

                              String  name;

                              String address;

                              //  can be used to initise instance var                    

                              void M1() //   non static method

                              {

                                             System.out.println("Calling M1()");

                                             // 1   refer the current class intance variebles i.e name , Address

                                             this.name = "Ramu";

                                             this.address = "Bng";

                                             System.out.println("name="+ name + ", address="+ address);

                                             //                          Ram                    Bangalore

                                             // 2 refer current class method -M2()

                                             this.M2();

                              }

                             

                              void M2() //   non static or Instance Method

                              {

                                             System.out.println("Calling M2()");

                              }

                             

                              Student4() //  Def const -   special   method -

                              {

                                             System.out.println("Def const is called ");

                              }             

                             

                              Student4(String sname, String sAddress) //   2 PC

                              {

                                             System.out.println(" PC is called");

                                            

                              }             

                             

                              public static void main(String[] args)

                              {

                                             System.out.println("in main");   

                                            

                                             // This  - is predefined k/w in java

                                             // can be used  -to refer current class instance var

                                             //                                       instance Method

                                             //                                      constructor

                                            

//                                          this.name =  "Ramu";// Cannot use this in a static context

                                             //  We cannot use this k/w in static  method . Main is static method

                                             //  this k//w cannot used in static method

                                             //     where should we use ?        

                                             // call method using this M1()

//                                          this.M1();

//                                          this.M1();  Cannnot use this k/w in static method

                                            

                                             // create obj for class Student4

                                                            Student4 s1 = new Student4();                                 

                               //   Call Def constr

                                             //   Def const is called

                                                           

                                             // caling M1()

                                                            s1.M1();

                                            

                                            

                                            

                                            

                              }

               }

o/p:

in main

Def const is called

Calling M1()

name=Ramu, address=Bng

Calling M2()

Calling current class 'default constr' using 'this' k/w :

package OOPSBasics;

public class Student4

{

               // instance variables       

               String  name;

               String address;

               void M1() //   non static method  or Instance method

               {

                              System.out.println("Calling M1()");

                              // 1   refer the current class intance variables i.e name , Address

                              this.name = "Ramu";

                              this.address = "Bng";

                              System.out.println("name="+ name + ", address="+ address);

                              // 2 refer current class method

                              this.M2();

                              // 3. call def constr

                              //                                          this();

                              ///Constructor call must be the first statement in a constructor

               }

               void M2() //   non static or Instance Method

               {

                              System.out.println("Calling M2()");

               }

               Student4() //  Def const -   special   method -

               {                            

                              System.out.println("Def const is called ");

                              // ???

               }             

               Student4(String sname, String sAddress) //   2 PC

               {      ///     Ramu            Bangalore

                              // call  Def constr using this

                              this();//  calls Dc

                              System.out.println(" PC is called");                         

               }             

               public static void main(String[] args) // static method

               {

                              System.out.println("in main");

                              // this can be used  -to refer current class instance variable -->

                              //                                           instance Method -->

                              //                                            constructor  -->

                              //  3 . calling current class constr

                              Student4 s1 = new Student4();//  calls Def constr

                              Student4 s2 = new Student4("Ramu",  "Bangalore");//   calls 2 PC

                              //                                          this();

                              // Dont use This k/w in static method

               }

}

o/p:

in main

Def const is called

Def const is called

 PC is called

Calling current class "Parameter constr" using "this" k/w :

package OOPSBasics;

public class Student5

{

               // instance variables       

                              String  name;

                              String address;

                              Student5() // Def constr

                              {

                                             // call 2 pc using this k/w

                                             this("Ramu", "Bangalore");

                                             System.out.println("Dc is called");                                                        

                              }

                             

                              Student5(String name, String address) //   2 PC

                              {      //name  =Ramu. address =Bangalore  here  - local var

                                             //   to differntiate b/w  instance variable and local variable - we must use this

                                             //  this - rerfers current class insatnce var

                                             this.name = name;

                                             this.address = address;

                                             System.out.println("name="+ name + ", address="+ address);

                                             //                          Ramu                   Bangalore

                              }             

                             

                              public static void main(String[] args)

                              {

                                             System.out.println("in main");   

                                             //  call 2 PC using this k/w

                                             // create obj for student class with ref variable -s5

//                                          this();

//                                          this("Ram", "Bangalore");//  Dont use this k/w inside static method

                                             Student5 s1 = new Student5();//  calls Def constr

                                            

                                            

                              }

               }

o/p:

-----

in main

name=Ramu, address=Bangalore

Dc is called

FAQ What is this ?

1.Def

2. to refer current class inst variable,  Method, constr

Ex4:

this k/w can be used to refer static variable  and static method also.

 

package OOPSBasics;

public class Student5

{

               // instance variables       

                              String  name;

                              String address;

                             

                              static String College ; //  static variable

                              static void SM1()  //  static metod

                              {

                                             System.out.println("Calling Sttaic method SM1()");

                              }

                             

                              void M2()

                              {

                                             // Note:

                                             // this k/w - we can  refer static variable  and static method also  (non static variable + non sttaic Method)

                                                            // College = "Jntu";

                                             this.College = "Jntu";

                             

                                             //  call static method       - SM1()

                                             this.SM1();

                              }

                                            

                              public static void main(String[] args)

                              {

                                             System.out.println("in main");   

                                             // create obj for Student class with ref variable -s5

                             

//                                          this.college = "Jntiu";// CE: Cannot use this in a static context

                                             // dont use this k/w in static method

                                            

//                                          this.SM1();// // CE: Cannot use this in a static context

                              // call M2()

                                             Student5 s1 = new Student5();

                                             s1.M2();

                                            

                              }

               }

o/p:

in main

Calling Sttaic method SM1()

Difference Between Default Constructor and Parameterized Constructor

Feature

Default Constructor

Parameterized Constructor

Definition

A constructor that does not accept any arguments.

A constructor that accepts one or more arguments.

Purpose

Used to initialize instance variables with default values.

Used to initialize instance variables with specific values provided by the arguments.

Arguments

Takes no arguments.

Takes one or more arguments.

Implicit Availability

If no constructors are defined, the compiler automatically provides a default constructor.

If at least one parameterized constructor is defined, a default constructor is not provided by the compiler.

 

 

 

Example

public ClassName()

{

}

public ClassName(String arg1, int arg2)

{

}

Initialization

Typically initializes instance variables to default values (e.g., null, 0, false).

Initializes instance variables to values passed as arguments.

 

FAQ: Difference Between Constructor and Method

Feature

Constructor

Method

Definition

Used to initialize instance variables with values.

A collection of statements to perform a specific task.

Naming

Must have the same name as the class.

Can have any name, same as or different from the class name.

Return Type

No return type (not even void).

Must have a return type (void, int, String, etc.).

Calling

Automatically called when an object is created.

Explicitly called using the method name and parentheses.

Purpose

To set up initial state for objects.

To define behaviors and actions.

 

package OOPSBasics;

public class Student6

{

               // instance variables       

                              String  name;

                              String address;

                             

                              Student6()// Def constr  //   2.  no return type    const name and class name must be same

                              { //  for constr -   we should not use return type  void, int, float, double, boolean,.... etc

                                             //

                                             //  to initise instance variable with some values

                                             System.out.println("Def const is called");

                                             name = "Raju";

                                             System.out.println("name="+name);

                              }

                             

                              void M2()  // Method

                              { ///   return type void, int , float.... etc

                                             System.out.println("Calling M2()");

                              }

                             

                              void Student6()//  Method   but not constr  as it has some return type 

                              {   //  Method name can be as same as class name or diff name

                                             System.out.println("Calling Student 6 -Method");

                              }

                                            

                              public static void main(String[] args)

                              {

                                             System.out.println("in main");   

                                             Student6  s5   = new Student6(); //3.  if we create obj for class, it calls Def constr by default

                                                                           //  we dont need to call constr explicitly 

                             

                                             // calling Method -explicitly by method name

                                             s5.M2();

                                            

                                             s5.Student6();

                                            

                              }

               }

o/p:

in main

Def const is called

name=Raju

Calling M2()

Calling Student 6 -Method

HW  create 'Employee' class  and define DC, 1 PC, 2 PC  , call all constructors from main()?

HW  in the above class ,   Define some instance variable,  static variables, instance methods, static methods, call all variable,  methods using this k/w ?

HW  Define some  constr for employee class ex:  DC, 1 PC,  3 PC  with 1 int param, char param, String param  and call constr  from main()

No comments:

Post a Comment

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...