final keyword function

1. Modified method with final can prevent overwriting by subclasses:

package abc;

public class Hello {
    
    
    // 无法被覆写:
    protected final void hi() {
    
    
    }
}

2. Modifying the field with final can prevent it from being reassigned:

package abc;

public class Hello {
    
    
    private final int n = 0;
    protected void hi() {
    
    
        this.n = 1; // error!
    }
}

3. Modifying local variables with final can prevent re-assignment:

package abc;

public class Hello {
    
    
    protected void hi(final int t) {
    
    
        t = 1; // error!
    }
}

4. Modification of class with final can prevent inheritance:

package abc;

// 无法被继承:
public final class Hello {
    
    
    private int n = 0;
    protected void hi(int t) {
    
    
        long i = t;
    }
}

Guess you like

Origin blog.csdn.net/Mr_zhang66/article/details/113180304