You are on page 1of 49

Final,static,abstract

Final Keyword

Final

• final keyword is used in different contexts. First of all, final is a non-access modifier
applicable only to a variable, a method or a class.
• When a variable is declared with final keyword, it’s value can’t be modified, essentially, a
constant. We must initialize a final variable, otherwise compiler will throw compile-time
error.
• When a class is declared with final keyword, it is called a final class. A final class cannot be
extended(inherited). Used to create immutable and to prevent inheritance.
• When a method is declared with final keyword, it is called a final method. A final method
cannot be overridden.
Final

Final keyword in java is used to restrict the user. The java final keyword can be used in many context.
The final keyword can be applied with the variables, 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.
Final Variable Example:

}
class Bike9 }
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
Final - method

If you make any method as final, you cannot override it.

class Bike
{
final void run() public static void main(String args[])
{ {
System.out.println("running"); Honda honda= new Honda();
} honda.run();
} }
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 10
0kmph");
}
Final - Class

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

final class Bike


{ public static void main(String args[])
} {
Honda1 honda= new Honda1();
class Honda1 extends Bike honda.run();
{ }
void run() }
{
System.out.println("running safely with 10
0kmph");
}
Initializing the final variable
class Gfg
// initializing CAPACITY
{
{
// a final variable
CAPACITY = 25;
// direct initialize
}
final int THRESHOLD = 5;

// static initializer block for


// a blank final variable
// initializing EULERCONSTANT
final int CAPACITY;
static{
EULERCONSTANT = 2.3;
// another blank final variable
}
final int MINIMUM;

// constructor for initializing MINIMUM


// a final static variable PI
// Note that if there are more than one
// direct initialize
// constructor, you must initialize
static final double PI =
MINIMUM
3.141592653589793;
// in them also
public GFG()
// a blank final static variable
{
static final double EULERCONSTANT;
MINIMUM = -1;
// instance initializer block for
}

}
In stringbuffer
class Gfg
{
public static void main(String[] args)
{
// a final reference variable sb
final StringBuilder sb = new StringBuilder("Geeks");

System.out.println(sb);

// changing internal state of object


// reference by final reference variable sb
sb.append("ForGeeks");

System.out.println(sb);
}
}
// final variable will throw compile-time error

class Gfg
{
static final int CAPACITY = 4;

public static void main(String args[])


{
// re-assigning final variable
// will throw compile-time error
CAPACITY = 5;
}
}
// Java program to demonstrate
// local final variable

// The following program compiles and runs fine

class Gfg
{
public static void main(String args[])
{
// local final variable
final int i;
i = 20;
System.out.println(i);
}
}
// Java program to demonstrate final
// with for-each statement

class Gfg
{
public static void main(String[] args)
{
int arr[] = {1, 2, 3};

// final with for-each statement


// legal statement
for (final int i : arr)
System.out.print(i + " ");
}
}
Final classes
final class A
{ // methods and fields }
// The following class is illegal.
Class B extends A
{ // COMPILE-ERROR! Can't subclass A }
Final methods
class A {
final void m1()
{ System.out.println("This is a final method.");
}}
class B extends A {
void m1()
{ // COMPILE-ERROR! Can't override.
System.out.println("Illegal!");
}}
final with Variables : The value of variable cannot be changed once initialized.filter_none
brightness_4
class A {
public static void main(String[] args)
{
// Non final variable
int a = 5;

// final variable
final int b = 6;

// modifying the non final variable : Allowed


a++;

// modifying the final variable :


// Immediately gives Compile Time error.
b++;
}
}
final with Class : The class cannot be subclassed. Whenever we declare any
class as final, it means that we can’t extend that class or that class can’t be
extended or we can’t make subclass of that class.filter_none
brightness_4
final class RR {
public static void main(String[] args)
{
int a = 10;
}
}
// here gets Compile time error that
// we can't extend RR as it is final.
class KK extends RR {
// more code here with main method
}
final with Method : The method cannot be overridden by a subclass. Whenever we declare any method
as final, then it means that we can’t override that method.filter_none
brightness_4
class QQ {
final void rr() {}
public static void main(String[] args)
{
}
}

class MM extends QQ {

// Here we get compile time error


// since can't extend rr since it is final.
void rr() {}
}
Note : If a class is declared as final then by default all of the methods present in that class are
automatically final but variables are not.
finally keyword

Just as final is a reserved keyword, so in same


way finally is also a reserved keyword in java
i.e, we can’t use it as an identifier. The finally
keyword is used in association with a try/catch
block and guarantees that a section of code
will be executed, even if an exception is
thrown. The finally block will be executed
after the try and catch blocks, but before
control transfers back to its origin.
// A Java program to demonstrate finally.
class Geek {
// A method that throws an exception and has finally.
finally
{
// This method will be called inside try-catch.
static void A() System.out.println("B's finally");
{ }
try { }
System.out.println("inside A"); public static void main(String args[])
throw new RuntimeException("demo"); {
}
try {
finally
A();
{
System.out.println("A's finally");
}
} catch (Exception e) {
}
System.out.println("Exception
// This method also calls finally. This method
caught");
// will be called outside try-catch. }
static void B() B();
{ }
try { }
System.out.println("inside B");
return;
}
Case 1 : Exceptions do not occur in
the program
class B {
public static void main(String[] args)
{
int k = 55;
try {
System.out.println("In try block");
int z = k / 55;
}

catch (ArithmeticException e) {
System.out.println("In catch block");
System.out.println("Dividing by zero but caught");
}

finally
{
System.out.println("Executes whether exception occurs or not");
}
}
}
Case 2 : Exception occurs and
corresponding catch block matches
// Java program to illustrate finally in
// Case where exceptions occur
// and match in the program
class C {
public static void main(String[] args)
{
int k = 66;
try {
System.out.println("In try block");
int z = k / 0;
// Carefully see flow dosen't come here
System.out.println("Flow dosen't came here");
}

catch (ArithmeticException e) {
System.out.println("In catch block");
System.out.println("Dividing by zero but caught");
}

finally
{
System.out.println("Executes whether exception occurs or not");
}
}
Case 3 : Exception occurs and
corresponding catch block not
found/match
// Java program to illustrate finally in
// Case where exceptions occur
// and do not match any case in the program
class D {
public static void main(String[] args)
{
int k = 15;
try {
System.out.println("In try block");
int z = k / 0;
}

catch (NullPointerException e) {
System.out.println("In catch block");
System.out.println("Dividing by zero but caught");
}

finally
{
System.out.println("Executes whether exception occurs or not");
}
}
}
finalize method

• It is a method that the Garbage


Collector always calls just before the
deletion/destroying the object which is
eligible for Garbage Collection, so as to
perform clean-up activity.
Case 1 : The object which is eligible for Garbage Collection,
that object’s corresponding class finalize method is going to
be executed
class Hello {
public static void main(String[] args)
{
String s = new String("RR");
s = null;

// Requesting JVM to call Garbage Collector method


System.gc();
System.out.println("Main Completes");
}

// Here overriding finalize method


public void finalize()
{
System.out.println("finalize method overriden");
}
}
Case 2 : We can call finalize method Explicitly then it will be
executed just like normal method call but object won’t be
deleted/destroyed
class Bye {
public static void main(String[] args)
{
Bye m = new Bye();

// Calling finalize method Explicitly.


m.finalize();
m.finalize();
m = null;

// Requesting JVM to call Garbage Collector method


System.gc();
System.out.println("Main Completes");
}

// Here overriding finalize method


public void finalize()
{
System.out.println("finalize method overriden");
}
}
Case 3 :Part a) If programmer calls finalize method, while
executing finalize method some unchecked exception rises.

class Hi {
public static void main(String[] args)
{
Hi j = new Hi();

// Calling finalize method Explicitly.


j.finalize();

j = null;

// Requesting JVM to call Garbage Collector method


System.gc();
System.out.println("Main Completes");
}

// Here overriding finalize method


public void finalize()
{
System.out.println("finalize method overriden");
System.out.println(10 / 0);
}
}
abstract keyword in java

abstract is a non-access modifier in java


applicable for classes, methods
but notvariables. It is used to achieve
abstraction which is one of the pillar of Object
Oriented Programming(OOP).
Abstract classes

• The class which is having partial


implementation(i.e. not all methods present
in the class have method definition).
• abstract class class-name{ //body of class }
Important rules for abstract methods:
• Any class that contains one or more abstract
methods must also be declared abstract
• The following are various illegal
combinations of other modifiers for methods
with respect to abstract modifier :
• final
• abstract native
• abstract synchronized
• abstract static
• abstract private
abstract class A
{ // abstract with method
// it has no body
abstract void m1();
// concrete methods are still allowed in abstract classes
void m2()
{
System.out.println("This is a concrete method.");
}
}
// concrete class B
class B extends A
{
// class B must override m1() method
// otherwise, compile-time exception will be thrown
void m1() {
System.out.println("B's implementation of m2.");
}
}

// Driver class
public class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
b.m1();
b.m2();
}
}
1) Like C++, in Java, an instance of an abstract class cannot
be created, we can have references of abstract class type
though.
abstract class Base {
abstract void fun();
}
class Derived extends Base {
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {

// Uncommenting the following line will cause compiler error as the


// line tries to create an instance of abstract class.
// Base b = new Base();

// We can have references of Base type.


Base b = new Derived();
b.fun();
}
}
2) Like C++, an abstract class can contain constructors in
Java. And a constructor of abstract class is called when an
instance of a inherited class is created. For example, the
following is a valid Java program.
// An abstract class with constructor
abstract class Base {
Base() { System.out.println("Base Constructor Called"); }
abstract void fun();
}
class Derived extends Base {
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {
Derived d = new Derived();
}
}
3) In Java, we can have an abstract class without any
abstract method. This allows us to create classes that
cannot be instantiated, but can only be inherited.
// An abstract class without any abstract method
abstract class Base {
void fun() { System.out.println("Base fun() called"); }
}

class Derived extends Base { }

class Main {
public static void main(String args[]) {
Derived d = new Derived();
d.fun();
}
}
4) Abstract classes can also have final methods (methods
that cannot be overridden). For example, the following
program compiles and runs fine.
// An abstract class with a final method
abstract class Base {
final void fun() { System.out.println("Derived fun() called"); }
}

class Derived extends Base {}

class Main {
public static void main(String args[]) {
Base b = new Derived();
b.fun();
}
}
static keyword in java
static is a non-access modifier in Java which is applicable for the
following:
blocks
variables
methods
nested classes
To create a static member(block,variable,method,nested class),
precede its declaration with the keyword static. When a member is
declared static, it can be accessed before any objects of its class are
created, and without reference to any object. For example, in below
java program, we are accessing static method m1() without creating
any object of Testclass.
// Java program to demonstrate that a static member
// can be accessed before instantiating a class
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}
• Static blocks
• If you need to do computation in order to
initialize your static variables, you can declare
a static block that gets executed exactly once,
when the class is first loaded. Consider the
following java program demonstrating use of
static blocks.
// Java program to demonstrate use of static blocks
class Test
{
// static variable
static int a = 10;
static int b;

// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}

public static void main(String[] args)


{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}
• Static variables
• When a variable is declared as static, then a
single copy of variable is created and shared
among all objects at class level. Static variables
are, essentially, global variables. All instances of
the class share the same static variable.
• Important points for static variables :-
• We can create static variables at class-level only.
See here
• static block and static variables are executed in
order they are present in a program.
// java program to demonstrate execution
// of static blocks and variables
class Test
{
// static variable
static int a = m1();

// static block
static {
System.out.println("Inside static block");
}

// static method
static int m1() {
System.out.println("from m1");
return 20;
}

// static method(main !!)


public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}

}
• Static methods
• When a method is declared with static keyword, it is
known as static method. The most common example of
a static method is main( ) method.As discussed above,
Any static member can be accessed before any objects
of its class are created, and without reference to any
object.Methods declared as static have several
restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.
// java program to demonstrate restriction on static methods
class Test
{
// static variable
static int a = 10;

// instance variable
int b = 20;

// static method
static void m1()
{
a = 20;
System.out.println("from m1");

// Cannot make a static reference to the non-static field b


b = 10; // compilation error

// Cannot make a static reference to the


// non-static method m2() from the type Test
m2(); // compilation error

// Cannot use super in a static context


System.out.println(super.a); // compiler error
}

// instance method
void m2()
{
System.out.println("from m2");
}

public static void main(String[] args)


{
// main method
}
}
• When to use static variables and methods?
• Use the static variable for the property that is
common to all objects. For example, in class
Student, all students shares the same college
name. Use static methods for changing static
variables.
• Consider the following java program
Autoboxing and Unboxing in Java

• Autoboxing: Converting a primitive value into an


object of the corresponding wrapper class is
called autoboxing. For example, converting int
to Integer class. The Java compiler applies
autoboxing when a primitive value is:
• Passed as a parameter to a method that expects
an object of the corresponding wrapper class.
• Assigned to a variable of the
corresponding wrapper class.
• Unboxing: Converting an object of a wrapper
type to its corresponding primitive value is called
unboxing. For example conversion of Integer to
int. The Java compiler applies unboxing when an
object of a wrapper class is:
• Passed as a parameter to a method that expects
a value of the corresponding primitive type.
• Assigned to a variable of the
corresponding primitive type.
// Java program to illustrate the concept
// of Autoboxing and Unboxing
import java.io.*;

class GFG
{
public static void main (String[] args)
{
// creating an Integer Object
// with value 10.
Integer i = new Integer(10);

// unboxing the Object


int i1 = i;

System.out.println("Value of i: " + i);


System.out.println("Value of i1: " + i1);

//Autoboxing of char
Character gfg = 'a';

// Auto-unboxing of Character
char ch = gfg;
System.out.println("Value of ch: " + ch);
System.out.println("Value of gfg: " + gfg);

}
}
/* Java program to illustrate autoboxing */
import java.io.*;
import java.util.*;

class GFG
{
public static void main (String[] args)
{
/* Here we are creating a list
of elements of Integer type.
adding the int primitives type values */
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
list.add(i);
}
}
/* Java program to illustrate autoboxing */
import java.io.*;
import java.util.*;

class GFG
{
public static void main (String[] args)
{
/* Here we are creating a list of elements
of Integer type. Adding the int primitives
type values by converting them into Integer
wrapper Object*/
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
list.add(Integer.valueOf(i));

}
}
// Java program to illustrate find sum
// of odd numbers using autobxing and unboxing
import java.io.*;
import java.util.*;
class GFG
{
public static int sumOfOddNumber(List<Integer> list)
{
int sum = 0;
for (Integer i : list)
{
// unboxing of i automatically
if(i % 2 != 0)
sum += i;
/* unboxing of i is done automatically
using intvalue implicitly
if(i.intValue() % 2 != 0)
sum += i.intValue();*/
}
return sum;
}

public static void main (String[] args)


{
/* Here we are creating a list of elements
of Integer type and adding the int primitives
type values to the list*/
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
list.add(i);

You might also like