In order to share the same method or variable of any given class, the static keyword is used.
It can be used for blocks, variables, methods, and nested classes.
Static variable –
A static variable is nothing but the class variable.
It is common for all objects of a class, or let’s say it is shared by all objects of a class, whereas the non-static variable is different for each object of a class.
E.g., static String name=” John”;
Static block –
To initialize static variables, a static block is used.
It gets executed only once after class is loaded or an object is created.
A class can contain multiple static blocks.
E.g. – static String name; static{ name = “Java”; }
Static method –
A static method is one that can be invoked without a created object of a class.
It can access static variables without using the object of the class.
It can access static and non-static methods directly. A non-static method can access the static method, while a static method can access the non-static method only through the object of a class.
Eg – public static void main(String args[]) { }
Static class –
A class can only be declared as static only if it is a nested class.
Non-static members of the Outer class are not accessible by the static class.
Eg – class Vehicle{ //Static class static class Car{ } }
this keyword –
“this” is basically just a reference variable referring to the current object.
It is used to eliminate the confusion between class attributes and parameters with the same name.
It can be used to –
refer class variable
invoke class method or constructor
passed as an argument in method or constructor
return current class object
E.g. –
this.name = name;
this.setName();
setName(this);
Person p = new Person(this);
return this;
super keyword –
The “super” keyword is a reference variable in java, used to refer parent class objects.
The super keyword can be used in three ways –
with variable –
It is used when a derived class and base class has the same data members. There is a possibility of ambiguity in such a case.
This keyword can be used to refer to the immediate parent class instance variable.
Eg – System.out.println(super.speed);
with method –
It is used when we want to call the parent class method, and parent & child class have same-named methods; then, to resolve ambiguity, we use the super keyword to invoke the immediate parent class method.
E.g., super.message();
with constructor –
To invoke the immediate parent class constructor, it is used with a constructor.
It can call both parametric as well as non-parametric constructors depending upon the situation.
Call to super() must be the first statement in a derived class constructor.