{"id":79073,"date":"2020-06-15T09:00:30","date_gmt":"2020-06-15T03:30:30","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=79073"},"modified":"2020-06-15T09:00:30","modified_gmt":"2020-06-15T03:30:30","slug":"java-final-keyword","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/","title":{"rendered":"Java Final Keyword, Variable, Method and Class"},"content":{"rendered":"<p>We know that there are 48 reserved keywords in Java and the final keyword is one of them. It is a keyword that can be used with entities in Java to restrict their use. We can use it with class, methods, variables.<\/p>\n<p>There are different uses of the Java final keyword for different entities. That is, the purpose of using the final keyword is different for class, variable, and method.<\/p>\n<p>In this article, we will discuss the final keyword in Java and learn to implement and use it with different parameters.<\/p>\n<h3>What is the Final Keyword in Java?<\/h3>\n<p>Java final keyword is a non-access specifier that is used to restrict a class, variable, and method. If we initialize a variable with the final keyword, then we cannot modify its value.<\/p>\n<p>If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a class as final, we restrict the other classes to inherit or extend it.<\/p>\n<p>In other words, the final classes can not be inherited by other classes.<\/p>\n<p>This was a brief introduction to a final keyword in Java. Now we will discuss the implementation of the final keyword with a variable, method, and class in Java. We will discuss the following topics in detail:<\/p>\n<p><strong>1.<\/strong> final variable<br \/>\n<strong>2.<\/strong> final class<br \/>\n<strong>3.<\/strong> final method<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/Final-Keyword.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-79089\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/Final-Keyword.jpg\" alt=\"Final Keyword in Java\" width=\"627\" height=\"323\" \/><\/a><\/p>\n<h3>Final Variable in Java<\/h3>\n<p>Once we declare a variable with the final keyword, we can\u2019t change its value again. If we attempt to change the value of the final variable, then we will get a compilation error.<\/p>\n<p>Generally, we can consider a final variable as a constant, as the final variable acts like a constant whose values cannot be changed.<\/p>\n<p>This rule was for the normal variables, what if we declare the reference variables as final? The restriction with the final reference variable is that we cannot change \u201cwhat the object is referring to\u201d but we can modify the object itself.<\/p>\n<p>We can&#8217;t just declare a variable as final without initializing it. That is, we have to give it an initial value while declaring a final variable. If we declare the final variable without initialization, then it is a blank final variable.<\/p>\n<p>But it is mandatory to initialize a final variable either during declaration or after declaration. If we leave it uninitialized, then we will get a compilation error.<\/p>\n<p><strong>Syntax of defining a final variable:<\/strong><\/p>\n<p>final int number = 10;\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\/\/final variable<br \/>\nfinal float value;\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\/\/blank final variable<br \/>\nstatic final double rate = 2.5;\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\/\/final and static variable<\/p>\n<h4><strong>Initializing Final Variable in Java<\/strong><\/h4>\n<p>As we know that a final variable cannot be left uninitialized, the following are the ways to initialize a final variable:<\/p>\n<p><strong>1.<\/strong> The most common approach is to initialize a final variable during its declaration. But if you don\u2019t initialize it while declaring it, then we call it as a blank final variable.<\/p>\n<p>The next two ways are the ways to initialize a blank final variable.<\/p>\n<p><strong>2.<\/strong> We can initialize a blank final variable inside an instance-initializer block or inside the constructor of the class. In case, there are many constructors in the class, then you need to initialize the final variable inside each constructor, else there will be an error.<\/p>\n<p><strong>3.<\/strong> We can initialize a blank final static variable inside a static block.<\/p>\n<p><strong>Code to understand Java final Variable:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.finalkeyword;\npublic class Vehicle {\n  \/\/declaring and initializing a final variable\n  final int speedlimit = 60;\n  void controlSpeed() {\n    \/\/Trying to change the value of the final variable will give an error\n    speedlimit = 150;\n  }\n  public static void main(String args[]) {\n    Vehicle obj = new Vehicle();\n    obj.controlSpeed();\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">com.techvidvan.finalkeyword.Vehicle.java:9: error: cannot assign a value to final variable speedlimit<br \/>\nspeedlimit = 150;<br \/>\n^<br \/>\n1 error<\/div>\n<p><strong>Code to understand the blank final variable:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.finalkeyword;\npublic class EmployeeDetails {\n  \/\/Blank final variable\n  final int id;\n\n  \/\/parameterized constructor\n  EmployeeDetails(int idNum) {\n    \/\/Blank final variable must be initialized in constructor\n    id = idNum;\n  }\n\n  void getDetails() {\n    System.out.println(\"Id of the Employee is: \" + id);\n  }\n\n  public static void main(String args[]) {\n    EmployeeDetails emp = new EmployeeDetails(154);\n    emp.getDetails();\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Id of the Employee is: 154<\/div>\n<p><strong>Code to understand the final reference variable:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.finalkeyword;\npublic class FinalReferenceVariable {\n  public static void main(String[] args) {\n    \/\/ declaring a final reference variable builder\n    final StringBuilder builder = new StringBuilder(\"Tech\");\n\n    System.out.println(builder);\n\n    \/\/ changing internal state of object reference by final reference variable builder\n    builder.append(\"Vidvan\");\n\n    System.out.println(builder);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Tech<br \/>\nTechVidvan<\/div>\n<h4>When to use Java Final Variable?<\/h4>\n<p>The normal variable and final variable differ only by one parameter that we can change the value of a normal variable once assigned, but we cannot change the value of a final variable once assigned.<\/p>\n<p>Therefore, we must use the final variables only for the assigning values that we want to remain constant throughout the execution of the program.<\/p>\n<h3>Final Method in Java<\/h3>\n<p>As earlier, we discussed the Final Keyword and How to declare the Final Variable. We can declare Java methods as Final Method by adding the Final keyword before the method name.<\/p>\n<p>The Method with Final Keyword cannot be overridden in the subclasses. The purpose of the Final Method is to declare methods of how&#8217;s definition can not be changed by a child or subclass that extends it.<\/p>\n<p><strong>Code to understand the final method in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.finalkeyword;\npublic class Parent {\n  final void final_method() {\n    \/\/definition of the Final Method\n  }\n}\npublic class Child extends Parent {\n  final void final_Method() \/\/ overriding the method from the parent class  \n  {\n    \/\/ another definition of the final method\n  }\n}<\/pre>\n<p>The above example of the Final Method generates a compile-time error.<\/p>\n<p>As the Parent class Final method was overridden by the Child class Final method; that is not possible in the Java programming language.<\/p>\n<h4>Purpose of Java Final Methods<\/h4>\n<p>The purpose of creating the final methods is to restrict the unwanted and improper use of method definition while overriding the method.<\/p>\n<p>Though it is not logically incorrect, it can change the meaning of the method and the reader might interpret it wrongly. Therefore, in such cases to prevent the unwanted method definitions, we declare methods as final.<\/p>\n<p>Suppose we make a class Animal and declare a non-final method sound() in it. Someone creates a Dog class and overrides the sound() method in it and prints the wrong sound of the Dog such as Meow or Roar, etc.<\/p>\n<p>This will make the wrong use of our method, so overcome this situation, we use the final method as shown in the below code:<\/p>\n<p><strong>Code to understand the purpose of the final Method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.finalkeyword;\npublic class Animal {\n  final void characteristics() {\n    int legs = 4;\n    int ears = 2;\n    int eyes = 2;\n    int tail = 1;\n    System.out.println(\"General Characteristics of an Animal are: \");\n    System.out.println(\"Legs: \" + legs);\n    System.out.println(\"Eyes: \" + eyes);\n    System.out.println(\"Ears: \" + ears);\n    System.out.println(\"Tail: \" + tail);\n  }\n}\npublic class Dog extends Animal {\n  final void sound() {\n    System.out.println();\n    System.out.println(\"Additional Characteristics:\");\n    System.out.println(\"Sound: Bhow Bhow\");\n  }\n  public static void main(String[] args) {\n    Dog d = new Dog();\n    d.characteristics();\n    d.sound();\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">General Characteristics of an Animal are :<br \/>\nLegs: 4<br \/>\nEyes: 2<br \/>\nEars: 2<br \/>\nTail: 1Additional Characteristics:<br \/>\nSound: Bhow Bhow<\/div>\n<h3>Final Class in Java<\/h3>\n<p>We can also declare a class with a final keyword in Java. When we declare a class as final, then we restrict other classes to inherit or extend it.<\/p>\n<p>In short, Java final class can\u2019t be extended by other classes in the inheritance. If another class attempts to extend the final class, then there will be a compilation error.<\/p>\n<p><strong>Code Snippet for final class:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">final class Tech {\n  \/\/ methods and variables of the class Tech\n}\n\nclass Vidvan extends Tech {\n  \/\/ COMPILE- TIME error as it extends final class\n}<\/pre>\n<p><strong>Code to understand Final Class:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.finalkeyword;\npublic class Vidvan extends Tech {\n  void test() {\n    System.out.println(\"My Method\");\n  }\n  public static void main(String[] args {\n    Vidvan obj = new Vidvan();\n    obj.test();\n  }\n}\nfinal class Tech {\n  \/\/code inside class\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Compile-time error<\/div>\n<h3>Conclusion<\/h3>\n<p>We come to the end of the article on the final keyword in Java. We learned that the final keyword can be used with variables, methods, and classes in Java to serve different purposes.<\/p>\n<p>You can use the final keyword with the variables, classes, and methods in special situations to restrict some things. We discussed how to use a normal variable and reference variable with a final keyword.<\/p>\n<p>We also learned how we can restrict a class from overriding a method. A class can also be made final which ensures that no other class can extend it. This was all about the final keyword in Java.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We know that there are 48 reserved keywords in Java and the final keyword is one of them. It is a keyword that can be used with entities in Java to restrict their use.&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":79088,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[2866,2867,2868,2869,2870,2871],"class_list":["post-79073","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-final-keyword-in-java","tag-java-final","tag-java-final-class","tag-java-final-keyword","tag-java-final-method","tag-java-final-variable"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Final Keyword, Variable, Method and Class - TechVidvan<\/title>\n<meta name=\"description\" content=\"Java Final Keyword - Learn what is final keyword in Java and how it can be implemented with varible, method and class in Java with examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Final Keyword, Variable, Method and Class - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Java Final Keyword - Learn what is final keyword in Java and how it can be implemented with varible, method and class in Java with examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-06-15T03:30:30+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Final-Keyword-in-java.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Final Keyword, Variable, Method and Class - TechVidvan","description":"Java Final Keyword - Learn what is final keyword in Java and how it can be implemented with varible, method and class in Java with examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/","og_locale":"en_US","og_type":"article","og_title":"Java Final Keyword, Variable, Method and Class - TechVidvan","og_description":"Java Final Keyword - Learn what is final keyword in Java and how it can be implemented with varible, method and class in Java with examples.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-06-15T03:30:30+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Final-Keyword-in-java.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java Final Keyword, Variable, Method and Class","datePublished":"2020-06-15T03:30:30+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/"},"wordCount":1109,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Final-Keyword-in-java.jpg","keywords":["Final keyword in Java","Java Final","Java Final Class","Java Final Keyword","Java Final Method","Java Final Variable"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/","url":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/","name":"Java Final Keyword, Variable, Method and Class - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Final-Keyword-in-java.jpg","datePublished":"2020-06-15T03:30:30+00:00","description":"Java Final Keyword - Learn what is final keyword in Java and how it can be implemented with varible, method and class in Java with examples.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Final-Keyword-in-java.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Final-Keyword-in-java.jpg","width":802,"height":420,"caption":"Java Final Keyword"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-final-keyword\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java Final Keyword, Variable, Method and Class"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/79073","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=79073"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/79073\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/79088"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=79073"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=79073"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=79073"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}