• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Summary: Final Keyword

In this tutorial we will learn the usage of final keyword. final keyword can be used along with variables, methods and classes. We will cover following topics in detail.

1) final variable
2) final method
3) final class

 

1. Final Variables

final variables are nothing but constants. We cannot change the value of a final variable once it is initialized. Lets have a look at the below code:

class Demo{  

   final int MAX_VALUE=99;
   void myMethod(){  
      MAX_VALUE=101;
   }  
   public static void main(String args[]){  
      Demo obj=new  Demo();  
      obj.myMethod();  
   }  
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The final field Demo.MAX_VALUE cannot be assigned

	at beginnersbook.com.Demo.myMethod(Details.java:6)
	at beginnersbook.com.Demo.main(Details.java:10)

2. Final Methods

A final method cannot be overridden. Which means even though a sub class can call the final method of parent class without any issues but it cannot override it.

final modifier indicates that the method may not be overridden in a derived class.

3. Final Class

We cannot extend a final class. 

When applied to a class, the final modifier indicates that the class can not be used as a base class to derive any class from it. 

posted @ 2016-01-19 13:01  neverlandly  阅读(240)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3