0% found this document useful (0 votes)
16 views

Z 9

Java
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
16 views

Z 9

Java
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 8
oa/112028 20.08, The "nal" Keyword in Java | Baeldung “ The “final” Keyword in Java Tiel u 2M Des performances & grande é agrever le budget informatiqu 1M Y thitos//ads freestarcom/? fated May 3, 2020 Written by: baeldung (httos.// wwwbaeldung.com/author/baeldung) Java (https:// wwwbaeldung.com/category/java) + Core Java (https://wwu:baeldung.com/tag/core-java) Java Keyword (https://www baeldung com/tag/java-keyword) Get started with Spring 5 and Spring Boot 2, through the Learn Spring course: > CHECK OUT THE COURSE (/s-course-start) hitpssww-baeldung.comiavacinal ve oa/112028 20.08, ‘The “inal Keyword in Java | Baeldung “ (https /ads freestarcom/? utm_campaign-branding&utm_.medium-banner&utm_source-baeldung.com&utm_content-baeldung.incontent 2 1. Overview While inhoritance enables us to reuse existing code. sometimes we do need to set limitations on ‘extensibility for various reasons: the final keyword allows us to do exactly that, In this tutorial. we'll take a look at what the final keyword means for classes, methods, and variables, 2. Final Classes Classes marked as final can't be extended. If we look at the code of Java core libraries, well find many final classes there. One example is the String class. Consider the situation ifwe can extend the String class, override any of its methods, and substitute all the String instances with the instances of our specific String subclass. ‘The result of the operations over String objects will then become unpredictable. And given that the String class is used everywhere, its unacceptable. That's why the String class is marked as final Performances 8 grande é cere budget informatiqu ™ (https://ads freestarcom/? ‘Any attemptto inherit from a final class will cause a compiler error. To demonstrate this, let's create the final class Cat public final class Cat { Oo private int weseht; 11 standard getter and setter And lets try to extend it public class BlackCet extends Cat { O ldung.comjava-final 28 oa/112028 20.08, ‘The “inal Keyword in Java | Baeldung al 16 complet Wellsee the sompiler error ¢, ‘The type BlackCat cannot subclass the final class Cat Oo Note that the final keyword in a class declaration doesn't mean that the objects of this class ar immutable. We can change the fields of Cat object freely: co net 0 assertéquals(1, cat.getweighe()); ‘We just cant extend it, If we follow the rules of good design strictly, we should create and document a class carefully or declare it final for safety reasons. However, we should use caution when creating final classes. Notice that making a class final means that no other programmer can improve it. Imagine that were using a class and dontt have the source code for it, and theres a problem with one method, IFthe class is final, we cant extend it to override the method and fix the problem. In other words, we lose extensibility, one of the benefits of object-oriented programming, 3. Final Methods Methods marked as final cannot be overridden. When we design a class and feel that a method shouldnt be overridden, we can make this method final. We can also find many final methods in Java core libraries. ‘Sometimes we dont need to prohibit a class extension entirely, but only prevent overriding of some methods. A good example of this is the Thread class. Its legal to extend it and thus create a custom thread class. But its /sAlived methods is final (httos//adsfreestarcom/? htipsitinww-baeldung,comjava-fnal 38 oart12028 20.08 ‘The “na Keyword in Java | Baeldung ‘This method checks if thread ig live. ts impossible to override the isAlived method correctly for many reasons, One of them is inat this Method is native. Native code is implemented in another programming language and is often specific to the operating system and hardware its running on. Let's create a Dog class and make its sound) method finat public class Dog { public Final void sound’) { Ww } Now let's extend the Dog class and try to override its sound method: public class BlackDog extends Dog { public void sound’) { } Weill see the compiler error: ~ overrides con. baeldung. finalkeyword.Dog. sound = Cannot override the final method from Dog Sound() method 1s Final and can’t be overridden Ifsome methods of our class are called by other methods, we should consider making the called methods final. Otherwise, overriding them can affect the work of callers and cause surprising results Four constructor calls other methods, we should generally declare these methods final for the above reason. ‘What's the difference between making all methods of the class finaland marking the class itself final? in the first case, we can extend the class and add new methods to it. In the second case, we cant do this, = >e TT Montez en puissance. hotaes Tout restive Cloud. oO aor es wel palin a SU a oe + performances & grande & wer le budget informatigu \ (httos//ads freestarcom/? 4. FinalVariables Variables marked as final cant be reassigned, Once a final variable is inlialized, it cant be altered, 4.1. Final Primitive Variables Let's declare a primitive final variable i, then assign 1 to it ‘And lets try to assign a value of 2 to it: htipsitmwwat ldung.comjava-final 48 oart12023 20.08, ‘The “nal Keyword in Java | Baeldung eablic vo / wiver!iratiars wotekddign thenontyonce) { oO Final int 4 i The compiler says: ‘The final local variable 4 may already have been assigned Oo 4.2. Final Reference Variables IFwe have a final reference variable, we cant reassign it either But this doesn't mean that the object it refers to is immutable, We can change the properties of this object freely. ‘To demonstrate this, let's declare the final reference variable cat and initialize it: jew Cat) 5 oO If we try to reassign it well see a compiler error final cat cot ‘The final local variable cat cannot be assigned. It must be blank and not using 2 compound Oo assignment But we can change the properties of Cat instance: ca. sete gE); O assertEquals(s, cat.getWeight()); 4:3. Final Fields Final fields can be either constants or write-once fields. To distinguish them, we should ask @ question —would we include this field if we were to serialize the object? If no. then its not part of the object. but a constant. Note that according to naming conventions, class constants should be uppercase, with components separated by underscore (".") characters: static final int MAK.NIDTH = 999; oO Note that any final field must be initialized before the constructor completes, htipsitinww-baeldung,comjava-fnal se oa/112028 20.08, ‘The “inal Keyword in Java | Baeldung For static fina! Felds, this means that we can intalize them ‘+ upon declaration as shown in the above example += in the static initializer block For instance final fields, this means that we can initialize them: = upon declaration + inthe instance initializer block '* inthe constructor Otherwise, the compiler will give us an error. 4.4. Final Arguments The final keyword is also legal to put before method arguments. A finalargument can't be changed inside a method pablic vold netioditiFinotrements(finst ft) Oo , The above assignment causes the compiler error: ‘The final local variable x cannot be assigned. It must be blank and not using a compound oO ‘assignment 5. Conclusion In this article, we learned what the final keyword means for classes, methods, and variables. Although we may not use the final keyword often in our internal code, it may be a good design solution. As always, the complete code for this article can be found in the GitHub project {https//github.com/eugenp/tutorials/tree/master/core-java-modules/core-java-lang-oop-modifiers) Get started with Spring 5 and Spring Boot 2, through the Learn Spring course: >> CHECK OUT THE COURSE (/Is-course-end) ldung.comjava-final oe o4/112023 20.08 ‘The “nal Keyword in Java | Baeldung Learning to build your API with Spring? Download the E-book (/rest-api-spring-gui 2 COMMENTS ide) yo Oldest = View Comments ‘COURSES ALL COURSES VALL-COURSES! ALL QULK COURSES (/ALL-BULK-COURSES) ALL QULK TEAM COURSES (/ALL-AULK-TEAM-COURSES! htipsitinww-baeldung,comjava-fnal 718 oa/112028 20.08, ‘The “inal Keyword in Java | Baeldung a SERIES ABOUT TERMS OF SERVICE (/TERMS-OF SERVICE) PRIVACY POLICY L/PRIVACY-POLICY COMPANY INFO (/BAELOUNG-COMPANY-INFO! htipsitinww-baeldung,comjava-fnal

You might also like