قراءة
عرض

Final Keyword in Java

Java, final keyword is applied in various contexts. The final keyword is a modifier means the final class can't be extended, a variable can't be modified, and also a method can't be override it means that an entity cannot later be changed.
Final classes
A final class cannot be extended. This is done for reasons of security (المنية والحماية) and efficiency (الكفاءة و الفعالية). Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final class are implicitly final.
The final class is declared in java as shown:
Example:
public final class MyFinalClass {...}
If we say:
public final class A {}
this means that A cannot be further extended or subclassed. This feature has a big implication. It allows control over a class, so that no one can subclass the class and possibly introduce anomalous behavior (سلوك غير طبيعي). For example, java.lang.String is a final class. This means, for example, that I can't subclass String and provide my own length() method that does something very different from returning the string length.
Final methods
You can declare some or all of a class's methods final. A final method can't be overridden by subclasses but it is still could be overloaded. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
A final method within a class could be declared in java as shown:
Example:
public class MyClass {
public final void myFinalMethod() {...}
}
You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object.
Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.

Final variables
The field declared as final behaves like constant. Means once it is declared, it can't be changed. Before compiling, only once it can be set; after that you can't change it's value. Attempt to change in it's value lead to exception or compile time error. We can declare final as:
Example:
public final double radius = 126.45;
public final int PI = 3.145;
The fields which are declared as static, final and public are known as named constants. Given below a example of named constant :
Example:
public class Maths{public static final double x = 2.998E8;}
A final variable can only be initialized once, either via an initializer or an assignment statement. It need not be initialized at the point of declaration: this is called a "blank final" variable.
A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases. (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.) Unlike the value of a constant, the value of a final variable is not necessarily known at compile time.
Example:
public class Sphere {

public static final double PI = 3.141592653589793; // pi is a universal constant, about as constant as anything can be.

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;
}

[...]
}
Any attempt to reassign radius, xpos, ypos, or zpos will meet with a compile error. In fact, even if the constructor doesn't set a final variable, attempting to set it outside the constructor will result in a compilation error.
To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a single one:
public final Position pos;
where pos is an object with three properties pos.x, pos.y and pos.z. Then pos cannot be assigned to, but the three properties can, unless they are final themselves.
Final method arguments
You can also declare method's argument as final. The final argument can't be modified by the method directly.


H.W. Answer the following:
Constructor cant be final, static and abstract…why?
Could you define a final class without final methods?
Could you use a set method to initialize the final attributes within a class.
Explain the difference between constant in C++ and final in Java.
Does the final method process the final variables?
Explain the blank final.
Discuss that " The value of a final variable is not necessarily known at compile time"
Lab:
Modify the example Polygon in Lec 16 using final for d1 and d2. Suppose that you have three polygons (2 rectangles and one triangle).

public abstract class Polygon {

protected final int d1,d2;
public Polygon(int a, int b){
d1=a;d2=b;}

public abstract int area();

public abstract void print();
}
public class Rectangle extends Polygon{
public Rectangle(int a,int b){
super(a,b);}
public int area(){return (d1*d2);}
public void print(){
System.out.println("rectangle");
System.out.println(d1+" "+d2);
}
}
public class Triangle extends Polygon {
public Triangle(int a,int b){
super(a,b);}
public int area(){return (d1*d2/2);}
public void print(){
System.out.println("triangle");
System.out.println(d1+" "+d2);


}
}
public class Main {
public static void main(String[] args) {
Polygon [] a=new Polygon[3];
for (int i=0;i<3;i++)
switch (i) {
case 0: a[i]=new Rectangle(5,4);break;
case 1: a[i]=new Triangle(7,8);break;
case 2: a[i]=new Rectangle(5,6);break;
}
for(int i=0;i<3;i++){
System.out.println(a[i].area());
a[i].print();}
}
}




رفعت المحاضرة من قبل: HS Alqaicy
المشاهدات: لقد قام عضوان و 60 زائراً بقراءة هذه المحاضرة








تسجيل دخول

أو
عبر الحساب الاعتيادي
الرجاء كتابة البريد الالكتروني بشكل صحيح
الرجاء كتابة كلمة المرور
لست عضواً في موقع محاضراتي؟
اضغط هنا للتسجيل