Final Classes in Java:
A class which is declared as "final" is called "Final Classes".A class which is already has all its implementation complete so none in the world should not be able to provide additional to original class. To achieve this scenario we should declare it as "final".
For example, Java api String class and System classes are declared as final.
Final Class Syntax:
public final class [class name]
Example:
package org.java.w3schools.finals;
/**
* @author Java-W3schools Blog
* @File Name Finalclass.java
*/
public final class Finalclass {
public void complete() {
System.out.println("Finalclass is complete");
}
}
Final class extends?
If final class appears in extends class anywhere than will raise compile time error. It shows that "Final class can not have any subclasses"./** * @author Java-W3schools Blog * @File Name FinalSubclass.java */ package org.java.w3schools.finals; public class FinalSubclass extends Finalclass { }Output:
Comiple time error(The type FinalSubclass cannot subclass the final class Finalclass)
Compile time error if we declare a class as both final and abstract class because a complete class could never be completed.
Refer Abstract classes in Java
/**
* @author Java-W3schools Blog
* @File Name AbstractFinalClass.java
*/
package org.java.w3schools.finals;
public abstract final class AbstractFinalClass {
}
Output:
Compile time error(The class AbstractFinalClass can be either abstract or final, not both).
A final class never has any subclasses as well the methods of a final class are never be overridden.
No comments:
Post a Comment
Please do not add any spam links in the comments section.