Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Final Keyword

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 306
    Comment on it

    Final is keyword that can be used before a class or method or a variable.

    Final Class

    They can not be subclassed and the method in it are by default final.

    public final class MyFinalClass {...}
    
    public class ThisIsWrong extends MyFinalClass {...}
    

    Final Method

    They can be override.This is done because to prevent unexpected behaviour from a subclass that is altering a method.

    public class Base
    {
        public       void m1() {...}
        public final void m2() {...}
    
        public static       void m3() {...}
        public static final void m4() {...}
    }
    
    public class Derived extends Base
    {
        public void m1() {...}  // Ok, overriding Base#m1()
        public void m2() {...}  // forbidden
    
        public static void m3() {...}  // OK, hiding Base#m3()
        public static void m4() {...}  // forbidden
    }
    

    Final Variable

    A final variable can be only initialized once.There is no need to again initialize at the time of declaration.

    The value of a final variable may not be known at the compile time.

    It is usually defined by a capital letter. public class Sphere {

        // pi is a universal constant, about as constant as anything can be.
        public static final double PI = 3.141592653589793;
    
        public final double radius;
        public final double xPos;
        public final double yPos;
        public final double zPos;
    
        Sphere(double x, double y, double z, double r) {
             radius = r;
             xPos = x;
             yPos = y;
             zPos = z;
        }
    
        [...]
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: