Skip to main content

Important Keywords: Final and Abstract:

Important Keywords: Final and Abstract:


Final:


 'final' keyword in java is used to restrict the user. It is applied to  'class' 'method' 'variable'

    a final class cannot be extended
    a final method cannot be overridden
    final fields, parameters, and local variables cannot change their value once set

*  a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.


Example:

class FinalExample{

   // blank final variable

   static final int Request_Number;

   static{

      Request_Number=4532134;

   }

   public static void main(String args[]){

      System.out.println(Example.Request_Number;);

   }

}


* A final method  can not be overridden in sub-class. You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time.


    class Bird{

      final void fly(){System.out.println("flying");}

    }

      

    class Eagle extends Bike{

     //  void fly(){System.out.println("flying High");}  // will show compile time //error due to this

      

       public static void main(String args[]){

       Eagle egl= new Eagle();

       egl.fly();

       }

    }



* If you make any class as final, you cannot extend it.

* Several classes in Java are final e.g. String, Integer and other wrapper classes


final class XYZ{

}

      

class ABC extends XYZ{  // will generate compile time error

   void demo(){

      System.out.println("ClassABC");

   }



Here are few benefits or advantage of using final keyword in Java:


1. It improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.


2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.


3. Final keyword allows JVM to optimized method, variable or class.



Final and Immutable Class in Java:

Final keyword helps to write immutable class. Immutable classes are the one which can not be modified once it gets created and String is primary example of immutable and final class.

Immutable classes offer several benefits one of them is that they are effectively read-only and can be safely shared in between multiple threads without any synchronization overhead.

 You can not make a class immutable without making it final and hence final keyword is required to make a class immutable in java.


Important points on final in Java

1. Final keyword can be applied to member variable, local variable, method or class in Java.

2. Final member variable must be initialized at the time of declaration or inside constructor, failure to do so will result in compilation error.

3. You can not reassign value to final variable in Java.

4. Local final variable must be initializing during declaration.

5. Only final variable is accessible inside anonymous class in Java.

6. Final method can not be overridden in Java.

7. Final class can not be inherited in Java.

8. Final is different than finally keyword which is used on Exception handling in Java.

9. Final should not be confused with finalize() method which is declared in object class and called before an object is garbage collected by JVM.

10. All variable declared inside java interface are implicitly final.

11. Final and abstract are two opposite keyword and a final class can not be abstract in java.

12. Final methods are bonded during compile time also called static binding.

13. Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".

14. Making a class, method or variable final in Java helps to improve performance because JVM gets an opportunity to make assumption and optimization.

15. As per Java code convention final variables are treated as constant and written in all Caps e.g.


16. Making a collection reference variable final means only reference can not be changed but you can add, remove or change object inside collection. For example:


17. Final method is inherited but you cannot override it

18. There could be final parameter also, you cannot change the value of it.



abstract

The “abstract” keyword can be used on classes and methods. A class declared with the “abstract” keyword cannot be instantiated, and that is the only thing the “abstract” keyword does. Example of declaring a abstract class:

abstract Seasons (String name);


* Abstract class  may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.


* An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void abstractMethodExample(String parameter1);


Methods in an interface that are not declared as default or static are implicitly abstract, so the abstract modifier is not used with interface methods.

A child class that inherits an abstract method must override it. If they do not, they must be abstract and any of their children must override it.

Comments

Popular posts from this blog

OBJECT class in Java

OBJECT class in Java : Object is at the top of class hierarchy in java. Every class in the Java system is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class. Mainly below methods are provided by Object class : public String toString() returns the string representation of this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public boolean equals(Object obj) compares the given object to this object. public int hashCode() returns the hashcode number for this object. public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of ...

Java Priority Queue sort using lambda expression

Priority Queue :     In Java  Priority Queue  is a  queue  which keeps its elements sorted as per their natural order( example in ascending orders for Integer, alphabetical a-z for alphabets) or using a custom Comparator at the time of creation you can custom sort it. It has most method  similar to a queue  add, clear, poll, peek As priority queue have to compare elements to keep in order so elements must be comparable otherwise, it will throw ClassCastException .  As null can not be compared so you are not allowed to insert null too A program to sort priority queue using Lambda function in Java           c lass   PriorityQueueLambdaJava { public List<Integer> KFrequent( int [] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for ( int j: nums) { map .put(j, map .getOrDefault(j, 0 ) + 1 ); } PriorityQueue<Map.Entry<Integ...

Important Keywords: Static, Continue,Break:

Important Keywords: Static, Continue,Break:  Static: The static keyword in java is used for memory management mainly.  The static keyword members belongs to the class rather than instance of the class. Following members can be declared as static: variable (also known as class variable) method (also known as class method) block nested class  static variables : We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe . Usually static variables are used with final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it as: ClassName.variableName //static variable example private static int a ge; public static String name; static methods: A static method belongs t...