Final Keyword in Java

The Final keyword in Java allows us to set limitations on accessibility to a code i.e it adds a restriction to access.

The static keyword can be used in the following context :

  1. Final Variable : to create constants
  2. Final Method : to prevent method overriding
  3. Final Class : to prevent inheritance

1. Java final variable

When a variable is declared with final keyword, its value can’t be modified, essentially, a constant. A final variable can be assigned value later, but only once

When to use a final variable :
final variables must be used only for the values that we want to remain constant throughout the execution of program.

Example:

              
public class FinalVariableClass {

    // a final variable direct initialization
    final int NUMBEROFITEMS = 5;

    // a blank final variable
    final int CART_CAPACITY;

    // an another blank final variable
    final int  MINIMUM;

    // a final static variable with direct initialization
    static final String COMPANY_NAME = "ProgrammerToday";

    // a  blank final static  variable
    static final double TEST_CONSTANT;

    // instance initializer block for initializing CART_CAPACITY
    {
        CART_CAPACITY = 10;
    }

    // static initializer block for initializing TEST_CONSTANT
    static{
        TEST_CONSTANT = 1.1;
    }

    // constructor for initializing MINIMUM
    // Note that if there are more than one
    // constructor, you must initialize MINIMUM
    // in them also
    public FinalVariableClass()
    {
        MINIMUM = 1;
    }

public static void main(String args[])
{
// re-assigning final variable will throw compile-time error
COMPANY_NAME = "ProgrammerToday_new";
}

}

2. Java final method

A Final method cannot be overridden

In a scenario where you feel that you method should not be overridden. So that it does not change your piece of code.

Example:

class A {
    final void display(){
        System.out.println("display method of parent class");
    }
 }
 
class B extends A{
 
    //'display()' cannot override 'display()' in 'A'; overridden method is final
    void display(){
        System.out.println("display method of child class");
    }
 
 } 
  

3. Java final class

A final class cannot be extended(inherited).

There are 2 uses of making a class final:

Example:

1. Is to prevent inheritance as the final class cannot be extended. e.g : wrapper classes like Integer, Float etc.

  final class FinalClass {
  }
  
  // The following class is not correct.
  class B extends FinalClass
  {
     // COMPILE-ERROR! Cannot inherit from final 'FinalClass'
  }
  

2. Is to make the class immutable for example like String.

FAQ , Questions and Answers

Q1. Can we initialize blank final variable ? If yes, then How ?

Sol. There are two ways to initialize blank final variable:

  1. Using constructor
  2. Using initialization block

Refer to the example above.

Q2. Can we declare a constructor as final ?

Sol. No, because it is never inherited.

Summary

In this article we learnt about Java Final Keyword and its various use cases. We saw it can be used as a variable, method and a class.
Hope you liked the article !


Static in Java

The Static keyword in Java is used mainly for memory management. The static keyword belongs to the class than an instance of the class, which means if you make a member as static then you can access it without creating a class object.

The static keyword can be used as :

  1. A variable
  2. A method
  3. A class
  4. A Block of statements

1. Java Static variable

It is common to all instances(or objects) of the class because it is a class level variable. It also means that the static variable is created only once and is shared among all the other instances of the class. A static variable can be accessed directly by the class name and doesn’t need any object.

<class-name>.<variable-name>

When and why we use static variable?

Scenario –

  1. Things like Database connection url , which may not change for a particular database
  2. An employee class, it has many employees with unique employee ids but belongs to the same company, hence company name can be put into a static variable.

Example:

public class StaticVariableTestClass {

  static int a1;
  static String a2;
  
  // This is a Static Method, calling static variables
  static void display() {
      System.out.println("Variable one is: " + a1);
      System.out.println("Variable two is: " + a2);
  }

  public static void main(String args[]) {
      display();
  }

}
  

OUTPUT

Variable one is: 0
Variable two is: null

Another Usecase : counter ++ using static variable, used as a counter variable.

2. Java Static method

  1. Static method in Java is a method which belongs to the class and not to the object. A static method can access only static data(not the instance variables)
  2. A static method can call only other static methods from it and cannot call a non-static method.
  3. A static method cannot refer to “this” or “super” keywords.
  4. A static method can be accessed directly by the class name , object instance is not needed.
<class-name>.<method-name>
public class TestStaticVariable {

  static int sum;

  // This is a Static Method
  static int sumOfTwoNumbers(int a1, int a2) {
    sum=a1+a2;
    return sum;
  }

  public static void main(String args[]) {
    sum=sumOfTwoNumbers(5,5);
    System.out.println("The sum of two numbers is : "+sum);
  }

}  

OUTPUT

The sum of two numbers is : 10

3. Java Static block

  1. Static block is a block where you can write statements to declare static variables.
  2. Static block is the first thing which JVM initializes on class load.
public class StaticBlock {

  static int number;

  static int square;

  // This is a Static Block
  // No matter where it is placed(top or bottom of code) it gets called 
  // before any other method
  static {
    System.out.println("** inside static block to initialize static variable **");
    number = 5;
  }

  // This is a Static Method
  static int squareOfANumber(int a1) {
    square = a1 * a1;
    return square;
  }

  public static void main(String args[]) {
    square = squareOfANumber(number);
    System.out.println("The square of a " + number + " is : " + square);
  }

}
    

OUTPUT

** inside static block to initialize static variable **
The square of a 5 is : 25

4. Java Static class

  1. A class can be made static only if it is a nested class which also means We can not declare top-level class with a static modifier.
  2. Nested static class doesn’t need reference of Outer class.
  3. A static class cannot access non-static members of the Outer class.
  4. A non static nested class is called the inner class.
             
public class OuterClass {

 private static String str = "ProgrammerToday";

   // nested class - as it is (inner + static)
   static class NestedStaticClass {

   // static method inside nested class
   static void displayName() {
     System.out.println("Book Name is : " + str);
   }

   // non-static method inside nested class
   void displayContent() {
     System.out.println("This book is about technology");
   }
   }

 public static void main(String[] args) {

 // way to call static method of nested class
 OuterClass.NestedStaticClass.displayName();

 // way to call non-static method of nested class by creating instance
 OuterClass.NestedStaticClass obj = new NestedStaticClass();
 obj.displayContent();

 }

}

OUTPUT

Book Name is : ProgrammerToday
This book is about technology

Summary

In this article we learnt about Java Static Keyword and its various use cases. We sar it can be used as a variable, method, block and a class.
Hope you liked the article !


Object Oriented Programming Java

Object Oriented Programming is a programming concept that works on the principle that objects are the most important part of your program.

The primary purpose of Object-oriented programming is to increase the flexibility and maintainability of programs.

Object-oriented programming (OOP) is nothing but that which allows the writing of programs with the help of certain classes and real-time objects.

The main aim of object-oriented programming is to implement real-world entities, for example, object, classes, abstraction, inheritance, polymorphism, etc.

1. Object

An Object is a bundle of data and its behaviour(often known as methods). Also it is an instance of a class.

An Object also means a real world entity such as a notebook/pen/pencil etc.

Example : A cat is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.

2. Class

A class is a group of similar Objects. It is a considered a blueprint using which you can create as many Objects as you like. An example could be having a class of Vehicles, and there can be Objects like 4 wheelers, 2 wheelers, etc and they will further have some properties like engine, make, model, year of manufacture, etc.

3. Constructor

A constructor is a block of statement which has same name as that of class and is used to initialize the class member properties.

Example :

public class OopsExample {

  int age;
  String name;
  
  //This is a Default constructor
  OopsExample(){
  this.name="John";
  this.age=35;
  }
  
  //And this one is Parameterized constructor
  OopsExample(String n,int a){
  this.name=n;
  this.age=a;
  }

  public static void main(String args[]){
       OopsExample obj1 = new OopsExample();
       OopsExample obj2 = new OopsExample("Jason", 40);
       System.out.println(obj1.name+" "+obj1.age);
       System.out.println(obj2.name+" "+obj2.age);
   }

}

OUTPUT

John 35
Jason 40

OOPs features : 4 of them with Examples

1. Encapsulation :
Wrapping up of data into a single unit is called Encapsulation. In terms of Java, if your are creating a Class with data members(variables) and behaviors(methods) then it means you are following encapsulation.

2. Abstraction :
Abstraction is a process when only the relevant data or information is shown to the user and other not necessary information is hidden from it.For Example, A car, In a car a driver/passenger knows only the relevant information which is required to drive the car, but how the engine is burning fuel inside, what and how it happens when you press the accelerator , what happens when you change the gear, a user doesn’t know.
He just have superficial knowledge or the use of certain equipment inside the car but not the inner functionality as a whole.

3. Polymorphism :
Polymorphism means having more than one form, In Object oriented programming language, Polymorphism refers to the ability of a variable, object or function to take on multiple forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

I. Static Polymorphism or compile time polymorphism : Achieved by method overloading, which means methods having the same name, same return type but different signature(number of parameters).

class MethodOverloading
{
    public void display(char ch)
    {
          System.out.println(ch);
    }
    public void display(char ch, int num)  
    {
          System.out.println(ch +“ - "+num);
    }
}
public class Test
{
    public static void main(String args[])
    {
        MethodOverloading obj = new MethodOverloading();
        obj.display('john');
        obj.display('john',40);
    }
} 

OUTPUT

john
john - 40

II. Dynamic Polymorphism or run time polymorphism : In dynamic polymorphism a call to overridden method is resolved at run time and that is why referred as run-time polymorphism.

class Animal{
  public void breed(){
  System.out.println("Default breed");
  }
}
public class Dog extends Animal{

  public void breed(){
  System.out.println("German Shepherd");
  }
  public static void main(String args[]){
  Animal obj = new Dog();
  obj.breed();
  }
} 

OUTPUT

German Shepherd

4. Inheritance :It is one of the code saving techniques, which helps in reducing the redundant code. It works by letting child class adapt properties of parent class, where the original class is called the parent class whereas the new one adapting the parents features is called the child class.
we use the keyword “extends” in classes and “implements” in interfaces.

Summary

In this article we learnt about Object Oriented Programming in Java and its 4 major concepts. We also learnt about Object, Class and its Constructor.
Hope you liked the article !