Wednesday, April 3, 2013

Java final field, method and class.

Here is some short example of:
- final field
- final method
- final class


package p_2013_04_03;

public class MyFinalExamples 
{
 // final field is defined and cannot be reassign 
 private final String myFinalString = "I am final string";
 
 // Final field cannot be assigned and if you inherit class you can't override final method 
 public final void setMyFinalString( String aFinalString )
 {
  this.myFinalString = aFinalString;
 }  
}

final class MyFinalExamples02 extends MyFinalExamples
{
 // Final methods can not be overridden 
 public void setUserName( String aUserName )
 {
  this.userName = aUserName;  
 }
}

// Misconception - can't subclass the final subclasses 
class MyFinalExamples03 extends MyFinalExamples02
{
 
}



Example of final field:
In line #9 we are trying to redefine the final field - but you can't do that.

Example of final method:
In line #9 there is final method that can't be overridden when that class will be inherited. So we are trying to override that method in line #18 in inherited class - that is not possible.

Example of final class:
In line #15 we have got final class which is inherited by class in line #25. It can't be done because final class cannot be inherited.

No comments: