Java – Public , Private, Protected, Static, This, Super and Final Keywords


1. This – keyword

What is a keyword in java ?

Its a reference variable , refers the current object.

What is this keyword in java ?

this keyword is a reference variable which refers the current object of the class.

What are the uses of this keyword ?

It can be used to refer instance variable of current class

It can be used to invoke or initiate current class constructor

It can be passed as an argument in the method call

It can be passed as argument in the constructor call

It can be used to return the current class instance

refer instance variable of current class

1. Variable Hiding

The this keyword here differentiates between the local variables and instance variables.

Example 1 :


class Eg3 {
  int a = 10;
  public static void main(String args[]) {
    Eg3 obj = new Eg3();
    obj.method(20);
    obj.method();
  }
  void method(int a) {
    a = 100;
    System.out.println("Value of Instance variable :" + this.a);
    System.out.println("Value of Local variable :" + a);
  }
  void method() {
    int a = 400;
    System.out.println("Value of Instance variable :" + this.a);
    System.out.println("Value of Local variable :" + a);
  }
}

Output :

Value of Instance variable :10

Value of Local variable :100

Value of Instance variable :10

Value of Local variable :400

2. Inside constructor 

This occurs if a Class has two overloaded constructors, one without argument and another with argument. 

Then the “this” keyword can be used to call constructor with argument from the constructor without argument. 

Example 1 :

public class Eg4 {
  Eg4() {
    this("Param for Defualt Construnctor");
    System.out.println("Inside Constructor without parameter");
  }
  Eg4(String str) {
    System.out.println("Inside Constructor with String parameter as = " + str);
  }
  public static void main(String[] args) {
    Eg4 obj = new Eg4();
  }

Output :

Inside Constructor with String parameter as = Param for Defualt Constructor

Inside Constructor without parameter

3. Inside Method

this keyword can also be used inside Methods to call another Method from same Class. 

Example 1 :

public class Eg5 {
  public static void main(String[] args) {
    Eg5 object = new Eg5();
    object.secondMethod();
  }
  void firstMethod(){
    System.out.println("Inside First Method");
    }
  void secondMethod(){
    System.out.println("Inside Second Method");
    this.firstMethod();// same as calling firstMethod()
  }
}

Output :

Inside Second Method

Inside First Method

2.Public – keyword

What is a public keyword ?

public is a java keyword also an access-modifier can be defined for class, methods and variables.

What happens when a class is declared as public ?

That particular class can be accessed from anywhere, including outside packages.

What happens when a method is declared as public ?

That particular method can be invoked not only from the enclosing class, but also from outside classes.

What happens when a variable is declared as public ?

That particular variable can be accessed and updated from outside classes.

Example 1 :

public class Eg1 {
    public String name;
    public void act() {
    }
}

Example 2 :

package packageName;
public class Class1
{
   public void output()
      {
          System.out.println("Sample output from Class1");
      }
}

Example 3 :

package packageNameTest;
import packageName.*;
class Class2
{
    public static void main(String args[])
      {
          Class1 object = new Class1();
          object.output();
      }
}

Output :

Sample output from Class1

3. Private – Keyword 

What is private keyword ?

It is a java keyword access-specifier which can accessible only within the class in which they are declared.

Example 1 :

class A
{ 
   private void display()
    {
        System.out.println("GeeksforGeeks");
    }
}

public class Eg1
{
   public static void main(String args[])
      {
          A obj = new A();
          //trying to access private method of another class
          obj.display();
      }
}

Output :

Eg1.java:15: error: display() has private access in A          

obj.display();             

^1 error

Since display() method is declared as private above error is thrown by the compiler.

4. Protected – Keyword

What is protected keyword ?

The protected keyword is an access modifier for method and variable of a class.

Where it can be accessed ?

if the variables are defined as protected , then it can be accessed from

  1. Within the enclosing class.
  2. Other classes in the same package as the enclosing class.
  3. Sub classes, regardless of packages.

Accessing from same package name but different class

The following class Class1, declares a protected variable name, inside package p1:

Example 1 :

package p1;

public class Class1 {
    protected String name;
}

The following class in the same package can access the variable name directly:

Example 2 :

package p1;

public class Class2 {
    void Employee() {
        Class1 obj = new Class1();
        obj.name = "APJ Abdul Kalam";    // access protected variable directly
    }
}

The following class is in different package but it extends the Class1 class so it can access the variable name directly:

Example 3 :

package p2;
import p1.Class1;

class Class2 extends Class1 {
    void showInfo() {
        name = "APJ Abdul Kalam";
    }
}

But the following class, in different package, cannot access the variable name directly:

Example 4 :


package p2;
import p1.Class1;

class Class3 {
    void hire() {
        Class1 obj = new Class1();
        // compile error, cannot acceess protected variable
        // from different package
        obj.name = "APJ Adbul Kalam";
    }
}

5. Static – Keyword

What is a static keyword ?

Static variable are used to maintain the static same location in the allocated memory location.

Its is mainly used to memory management purpose.

We can apply java static keyword with variables, methods, blocks and nested class.

The main use of static variable will make our program memory efficient (it saves memory).

a. Java static variable

A static variable is a class variable and doesn’t belong to Object/instance of the class.

Example 1 :

public static variableName;
private static variableName;

if static variable is defined as public , it can be accessed by any objects, methods , other classes.

if static variable is defined as private, it can be accessed only inside that particular class.

b. Java static methods

Methods are defined by static keyword which belongs only to that particular class and not to class instances.

We can access static methods with reference to class name, without creating object. 

Example 1 :

class Eg1{
   static int i = 10;
   static String something = "India is my country";
   //This is a static method
   public static void main(String args[])
   {
       System.out.println("The value of i = "+i);
       System.out.println("The value of something = "+something);
   }
}

Output :

The value of i = 10

The value of something = India is my country

c. Java Static blocks

Static block is used to initialise static variables of the class also used to create static resources when class is loaded.

Non-static variables are not accessed inside the static block.

Example 1 :

class Eg1{
   static int a;
   static String name;
   static{
      a = 10;
      name = "APJ";
   }
   public static void main(String args[])
   {
      System.out.println("The value of a = "+a);
      System.out.println("The value of name: "+name);
   }
}

Output :

The value of a = 10

The value of name: APJ

d. Java – static class

A class can be made static only if it is a nested class.

Nested static class doesn’t need reference of Outer class

A static class cannot access non-static members of the Outer class

Example 1 :


class Eg1{
   private static String name = "APJ Abdul Kalam";
   //Static class
   static class Class1{
        //non-static method
        public void showInfo() {
           System.out.println(name);
        }
   }
   public static void main(String args[])
   {
        Eg1.Class1 obj = new Eg1.Class1();
        obj.showInfo();
   }
}

Output :

APJ Abdul Kalam

6. Super – keyword

What is super keyword ?

super keyword in java is a reference variable that is used to refer parent class objects.

a. super keyword with variables

Example 1 :

class Class1
{ 
   int num = 10;
}
//Child class or subclass or derived class
class Class2 extends Class1
{
   /* The same variable num is declared in the Class2
    * which is already present in the Class1
    */
    int num = 100;
    void printNumber(){
        System.out.println("The value of num = "+num);
    }
    public static void main(String args[]){
        Class2 obj= new Class2();
        obj.printNumber();
    }
}

Output :

The value of num = 100

b. Use of super with variables: 

Use of super keyword When a derived class and base class has same data members.

Example 1 :

class Class2
{
    int age = 100;
}
class Class1 extends Class2
{
    int age = 150;

    void display()
    {
        System.out.println("age = " + super.age);
    }
}
class Eg2
{
    public static void main(String[] args)
    {
        Class1 obj = new Class1();
        obj.display();
    }
}

Output :

age = 100

c. Use of super with methods: 

Whenever a parent and child class have same named methods then we use super keyword. 

Example 1 :

class Class1
{ 
    void printInfo()
    {
        System.out.println("This is called inside Class1");
    }
}
class Class2 extends Class1
{
    void printInfo()
    {
        System.out.println("This is called inside Class2");
    }
    void showInfo()
    {
        printInfo();
        super.printInfo();
    }
}
class Eg2
{
    public static void main(String args[])
    {
        Class2 obj = new Class2();
        obj.showInfo();
    }
}

Output :

This is called inside Class2

This is called inside Class1

d. Use of super with constructors: 

super keyword can also be used to access the parent class constructor. 

Super keyword can call both parametric as well as non parametric constructors depending upon the situation.

Example 1 :

class Class1
{
    Class1()
    {
        System.out.println("Class1 Constructor");
    }
}
class Class2 extends Class1
{
    Class2()
    {
        super();
        System.out.println("Class2 Constructor");
    }
}
class Eg2
{
    public static void main(String[] args)
    {
        Class2 obj = new Class2();
    }
}

Output :

Class1 Constructor

Class2 Constructor

7. Final – Keyword 

What is final keyword ?

Final is a java keyword, and when a variable is declared with final keyword, it’s value can’t be modified, its constant.

Why we use final keyword ?

when final keyword is used in a method which indicates that method cannot be overridden by subclasses.

Syntax :

final data-type variableName;

or

final data-type variableName = "something";

a. Final Keyword as Variable 

We cannot change the value of a final variable once it is initialised. 

If we try to change the variable value, JVM throws the compilation error.

Example 1 :

class Eg2{
  
   final int AGE=100;
   void newMethod(){
      AGE=111;
   }
   public static void main(String args[]){
      Eg2 obj = new  Eg2();
      obj.newMethod();
   }
}

Output :

Eg2.java:5: error: cannot assign a value to final variable AGE

AGE=111;

^1 error

b. Final keyword variable as blank

What is blank variable ?

A final variable that is not initialised at the time of declaration is known as blank final variable. 

We must initialise the blank final variable in constructor of the class otherwise it will throw a compilation error. 

Example 1 :

class Eg2{
   final int AGE;
   Eg2(){
      AGE=100;
   }
   void newMethod(){
      System.out.println("The value of age declared inside the constructor = "+ AGE);
   }
   public static void main(String args[]){
      Eg2 obj = new  Eg2();
      obj.newMethod();
   }
}

Output :

The value of age declared inside the constructor = 100

c. static final blank variable 

A static final variable that is not initialised during declaration can only be initialised in static block. 

Example 1 :

class Eg2{
   //static blank final variable
   static final int AGE;
   static{
      AGE=25;
   }
   public static void main(String args[]){
      System.out.println("The value of AGE = " +Eg2.AGE);
   }
}

Output :

The value of AGE = 25

d. Final as method 

A final method cannot be overridden, even though a sub class can call the final method of parent class without any issues but it cannot override it.

Example 1 :

class Class2{
   final void showInfo(){
      System.out.println("Calling Class2 Method");
   }
}  
class Class1 extends Class2{
   public static void main(String args[]){
      Class1 obj = new Class1();
      obj.showInfo();
   }
}

Output :


Calling Class2 Method

e. Final as Class

We cannot extend the final class

Example 1 :

final class Class2{
}

class Class1 extends Class2{
   void showInfo(){
      System.out.println("Printing inside the Class1");
   }
   public static void main(String args[]){
      Class1 obj= new Class1();
      obj.showInfo();
   }
}

Error :

Eg2.java:4: error: cannot inherit from final Class2

class Class1 extends Class2{

 ^1 error

The type Class1 cannot subclass the final class Class2