1. What is the use of final keyword in java?
2. What is the main difference between abstract method and final method?
5.Can we declare interface as final?
6. Is it possible to declare final variables without initialization?
7. Can we declare constructor as final?
8.What will happen if we try to override final methods in sub classes?
- By using final keyword we can make
- Final class
- Final method
- Final variables
- If we declare any class as final we can not extend that class
- If we declare any method as final it can not be overridden in sub class
- If we declare any variable as final its value unchangeable once assigned.
2. What is the main difference between abstract method and final method?
- Abstract methods must be overridden in sub class where as final methods can not be overridden in sub class
- If a class needs some security and it should not participate in inheritance in this scenario we need to use final class.
- We can not extend final class.
- Compile time error will come.
- package com.finalkeywordintweviewprograms;
- public final Class SuperDemo{
- int a,b;
- public void show() {
- System.out.println(a);
- System.out.println(b);
- }
- }
- package com.finalkeywordintweviewprograms;
- public Class Sample extends SuperDemo{ //The type Sample cannot subclass the final class
- SuperDemo
- }
5.Can we declare interface as final?
- No We can not declare interface as final because interface should be implemented by some class so its not possible to declare interface as final.
6. Is it possible to declare final variables without initialization?
- No. Its not possible to declare a final variable without initial value assigned.
- While declaring itself we need to initialize some value and that value can not be change at any time.
- package com.finalkeywordintweviewprograms;
- public final Class Sample{
- final int x=12,y=13;
- public void Method() {
- x=25;// compile time error:The final field Super.x cannot be assigned
- y=33;// compile time error: The final field Super.y cannot be assigned
- }
- }
7. Can we declare constructor as final?
- No . Constructors can not be final.
8.What will happen if we try to override final methods in sub classes?
- Compile time error will come :Cannot override the final method from Super class
- Yes we can create object for final class.
- String (for example)
No comments