Final
Final classes / methods cannot be extended / overriden.
/**
* A final class cannot be exended.
* A final method cannot be overriden.
*/
package com.minte9.oop.final_keyword;
public class Final {
public static void main(String[] args) {
new B();
}
}
class A {
public final void getName() { // Look Here
}
}
final class B extends A {
/*
public void getName() {
// Error: override final method
}
*/
}
/*
class C extends B {
// C cannot subtype finalclass B
}
*/
Constants
Fields that are static and final are constants (it can never change).
/**
* A static final variables is a constant.
* It cannot be changed.
*/
package com.minte9.oop.final_keyword;
public class Constants {
public static void main(String[] args) {
new MyClass(); // 25
}
}
class MyClass {
public static final int FOO = 25; // Look Here
public MyClass() {
System.out.println(FOO);
// FOO++; // Compile Error - Look Here
}
}
Last update: 450 days ago