Java Interview Question

 

                              Java
                        Interview Questions:

                        Difference between final finally and finalize()

 

Final :

final is modifier is applicable for classes methods and the variables.

 Ã If we declared variable as final then it will become constants.

 Ã if we declared method as final. In child class we can’t override this method.

àif we declared class  as final then we can’t extends(inherited) this class.

 

 

 

//If we declared variable as final then it will become constants.

 

public class ClassFinal {

    public static void main(String[] args) {

    

      final int a = 5;

      a = 4;                 // we can't reassign variable value , becaz this variable is final....

    }

}

 

OUTPUT: error

//if we declared method as final. In child class we can’t override this method.

 

 class parent

{

    public final void m1()

    {

        System.out.println("parent");

    }

}

 

class child extends parent

{

    public void m1()

    {

        System.out.println("child");

    }

}

 

public class ClassFinal {

    public static void main(String[] args) {

    

        child c = new child();

        c.m1();

      

    }

}

 

OUTPUT: Error…

 

 

//if we declared class  as final then we can’t extends(inherited) this class.

 

 final class parent

{

    public  void m1()

    {

        System.out.println("parent");

    }

}

 

class child extends parent

{

    public void m1()

    {

        System.out.println("child");

    }

}

 

public class ClassFinal {

    public static void main(String[] args) {

    

        child c = new child();

        c.m1();

      

    }

}

 

 

OUTPUT: Error ..

 

 

 

Finally:

finally  is a block always associated with try – catch block

To maintain clean up code.

try

{

  // risky code

}

catch( Exception e)

{

  // handle the exception in try block

}

Finally

{

  // clean up code

 // close the file…like that..

}

 

 

 

 

 

 

 

Finalize():

Finalize() is the method which is always called by  garbage collector just before destroying an object

To perform clean up activities.

 

NOTE: finally meant for cleanup activities related to try block.

Where as finalize() meant for cleanup activities related to the object.

Comments

Popular posts from this blog

Practical slips programs : Machine Learning

Full Stack Developement Practical Slips Programs

Android App Developement Practicals Programs