this keyword
What is this keyword?
- It is a predefined keyword supplied by java compiler (javac).
- this keyword is used to solve variable name conflicts.
- For JVM this keyword means current object address.
- For programmer this keyword can be used to refer instance variable.
- Never use this keyword in static methods. (it's not recommended)
What is the use of this keyword?
- this keyword is used to solve variable name conflicts.
eg. public class A{
public int i = 0;
public A(int i )
{
System.out.println(i); //here output will contain the value of local variable i.
System.out.println(this.i); // here value of instance variable i will be printed. - this keyword can be used to call same class constructor, from other constructor.
- this keyword can also be used to call same class method.
Rules of Compiler and JVM:-
Compiler Rule :- For every non-static method definition, compiler will add first parameter as this keyword.
JVM Rule :- For every non-static method definition, JVM passes current object address as first parameter.
eg. public class A{ public class MyProgram{
public A(A this,int i ) {
{ int i =5;
A a1 = new A(0x100, i);
-------CODE------
}
In class A (A this) is added by compiler, while in class <MyProgram> some address of the current object of A i.e suppose 0x100 is added by JVM while executing the program.
Rules for using this() constructor call :-
- this() constructor call should always be the first line of the constructor.
- A normal method can't use this() to call constructor.
- Iterative constructor calls are not possible.
Note :- It removes code duplicacy.
Static Keyword
What is static keyword?
- It is a predefined keyword supplied by java compiler.
- It is used before variables and methods to make them static.
- static variables are related to class variables.(i.e they can be accessed by using class Name and . operator)
- static variables will be created only once at the time of class loading.
- static variables are stored in data segment.
- Just like we access static variables with class name, Similarly we can access static method with class Name.
- A static method can access only
a) static variables and
b)static methods of the same class.
Use of static variable and static method:-
- Static variables are used when we need to share a common data with different objects of the class. E.g. For a student class maintained for a particular college, the college name can be made static as it will remain same for every instance of student.
- Static methods are used to access static variables. These are also used in Singleton Classes which I will cover later.
Static Initialization Block:-
A static block looks like this:-
static
{
---------CODE--------
}
static block is executed only once i.e at class loading time.
Note:- While loading a class JVM follows a priority, which is given below:-
- Static Variable
Static Block
Static Method
Comments
Post a Comment