Automation QA Testing Course Content

Java final keyword

FINAL KEYWORD:

In Java, the final keyword is used to denote constants. It can be used with variables, methods, and classes.

Once any entity (variable, method or class) is declared final, it can be assigned only once. That is,

  • the final variable cannot be reinitialized with another value
  • the final method cannot be overridden
  • the final class cannot be extended

1. Java final Variable

In Java, we cannot change the value of a final variable. For example,

class Main {
  public static void main(String[] args) {

    // create a final variable
    final int AGE = 32;

    // try to change the final variable
    AGE = 45;
    System.out.println("Age: " + AGE);
  }
}

In the above program, we have created a final variable named age. And we have tried to change the value of the final variable.

When we run the program, we will get a compilation error with the following message.

cannot assign a value to final variable AGE
    AGE = 45;
    ^

Note: It is recommended to use uppercase to declare final variables in Java.


2. Java final Method

Before you learn about final methods and final classes, make sure you know about the Java Inheritance.

In Java, the final method cannot be overridden by the child class. For example,

class FinalDemo {
    // create a final method
    public final void display() {
      System.out.println("This is a final method.");
    }
}

class Main extends FinalDemo {
  // try to override final method
  public final void display() {
    System.out.println("The final method is overridden.");
  }

  public static void main(String[] args) {
    Main obj = new Main();
    obj.display();
  }
}

In the above example, we have created a final method named display() inside the FinalDemo class. Here, the Main class inherits the FinalDemo class.

We have tried to override the final method in the Main class. When we run the program, we will get a compilation error with the following message.

 display() in Main cannot override display() in FinalDemo
  public final void display() {
                    ^
  overridden method is final

3. Java final Class

In Java, the final class cannot be inherited by another class. For example,

// create a final class
final class FinalClass {
  public void display() {
    System.out.println("This is a final method.");
  }
}

// try to extend the final class
class Main extends FinalClass {
  public  void display() {
    System.out.println("The final method is overridden.");
  }

  public static void main(String[] args) {
    Main obj = new Main();
    obj.display();
  }
}

In the above example, we have created a final class named FinalClass. Here, we have tried to inherit the final class by the Main class.

When we run the program, we will get a compilation error with the following message.

cannot inherit from final FinalClass
class Main extends FinalClass {
                   ^
For a class, the final keyword means that the class cannot have subclasses, i.e. inheritance is forbidden... This is useful when creating immutable (unchangeable) objects. For example, the String class is declared as final.
public final class String {
}

class SubString extends String { // Compilation error
}
I should also note that the final modifier cannot be applied to abstract classes (those with the keyword abstract), because these are mutually exclusive concepts. For a final method, the modifier means that the method cannot be overridden in subclasses. This is useful when we want to prevent the alteration of the original implementation.
public class SuperClass {
    public final void printReport() {
        System.out.println("Report");
    }
}

class SubClass extends SuperClass {
    public void printReport() { //Compilation error
        System.out.println("MyReport");
    }
}

Best example is

Math final class of java.

Syntax of final class

final class clsName

{

     // body of class

}


class PersonalLoan{

 public final String getLoan(){

     return "personal loan";

 }

}

class CheapPersonalLoan extends PersonalLoan{

    @Override

    public final String getLoan(){

        return "cheap personal loan"; //compilation error: overridden method is final

   }

}

===================================================

this:it is a referencevaiable it refers to current object.

1)this keyword can be used to refer current class instance variable.

2)this keyword can be used to invoke current class constructor.

3)this keyword can be used to invoke current class method

----------------------------------------------------------------

Super:

it is a referencevaiable, it refers to immediate parent class objects.

1)super is used to refer immediate parent class instance variable—super.parentclassinstancevariable;

2)it is used to invoke parent class constructor—super()

3)it is used to invoke parent class method.(super.parentclassmethod())

NOTE:both this, super keywords cannot be used inside the Constructor at the same timefrequently use final variables.

package oopsexamples;

public class Bike extends Vehicle {

          int speed;

          Bike(int speed){

                   super();

                   this.speed=speed;

          }

         

          public void run(int speed){

                   System.out.println("bike is running with speed:"+this.speed);

          }

         

          public void details(){

                   System.out.println("vehicle instance variable"+super.speed);

                   System.out.println("bike class instance variable:"+this.speed);

                   super.run(super.speed);

                   this.run(speed);

                

          }

          public static void main(String[] args) {

                   Bike b=new Bike(230);

                   /*b.run(100);

                   Vehicle v=new Bike();

                   v.run(150); //upcasting*/

                   b.details();

          }

}

package oopsexamples;

public class Vehicle {

          int speed;

          public Vehicle(){

                   System.out.println("this is vehicle default constructor");

          }

          public Vehicle(int speed){

                   this();

                   this.speed=speed;

          }

          public void run(int speed){

                   System.out.println("vehicla is running on speed:"+(this.speed+speed));

          }

          public static void changeGear(){

          System.out.println("change the gear fro m2 t otop");       

          }

          public static void main(String[] args){

                   Vehicle v=new Vehicle(150);

                   v.run(50);

                   v.changeGear();

    }

       

}

=============================================================
Object class: This is a super class for all the java classes.it is the topmost class of java. if we dont know the datatype of any element that element datatype is Object.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.

Object class Methods:
MethodDescription
public final Class getClass()returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
public int hashCode()returns the hashcode number for this object.
public boolean equals(Object obj)compares the given object to this object.
protected Object clone() throws CloneNotSupportedExceptioncreates and returns the exact copy (clone) of this object.
public String toString()returns the string representation of this object.
public final void notify()wakes up single thread, waiting on this object's monitor.
public final void notifyAll()wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws InterruptedExceptioncauses the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws InterruptedExceptioncauses the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait()throws InterruptedExceptioncauses the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwableis invoked by the garbage collector before object is being garbage collected.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.