donaricano-btn

 Final keyword

- It in java is used to restrict the user

- Stop Value Change

- Stop Method Overridding

- Stop Inheritance


1. How to use

- final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable

- blank final variable

a. It can be initialized in the constructor only

b. It can be static also which will be initialized in the static block only


2. Final variable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Student {
     
    final int grade = 100;
     
    void run(){
        grade = 90;
    }
     
    public static void main(String[] args){
         
        Student aa = new Student();
        aa.run();
    }
}

Complile time error

Final variable once assigned a value can never be changed


3. Final method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Teacher{
    final void run(){
        System.out.println("Teacher");
    }
}
public class Student extends Teahcer{
    void run(){
        System.out.println("Student");
    }
     
    public static void main(String[] args){
         
        Student aa = new Student();
        aa.run();
    }
}
 

Complile time error

- It cannot override it


4. Final class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
final class Teacher{
     
    final void run(){
        System.out.println("Teacher");
    }
}
 
public class Student extends Teacher{
     
     
    public static void main(String[] args){
         
        new Student().run();
    }
     
}
 

Complile time error

- You cannot extend it


5. Question

1) Is final method inherited?

- final method is inherited but you cannot override

2) What is blank or uninitialized final variable?

- A final variable that is not initialized at the time of declaration is known as blank final variable

- It can be initialized only in constructor

 

1
2
3
4
5
class Student{
  int id;
  String name;
  final String PAN_CARD_NUMBER;
}

3) static blank final variable

- A static final variable that is not initialized at the time of declaration is known as static blank final variable

- It can be initialized only in static block

 

1
2
3
4
5
6
7
8
9
class A{
  static final int data;
  static{
    data = 50;
  }
  public static void main(String[] args){
    System.out.println(A.data);
  }
}

4) What is final parameter?

- You cannot change the value of final it

 

1
2
3
4
5
6
7
8
9
class A{
    int cube(final int n){
       n = n +2;
    }
  public static void main(String[] args){
     A aa = new A()
     aa.cube(5);
  }
}

Complile time error

5) Can we declare a constructor final?

- No, because is never inherited



'Back-End > Java_1' 카테고리의 다른 글

[Java] Static Binding and Dynamic Binding  (0) 2016.09.08
[Java] Runtime Polymorphism  (0) 2016.09.08
[Java] Instance initializer block  (0) 2016.09.07
[Java] Super keyword  (0) 2016.08.25
[Java] Covariant Return type  (0) 2016.08.24
블로그 이미지

리딩리드

,