Search code examples
javainheritancefinalextends

Is it possible to extend a final class in Java?


On possible duplicate:

This thread is not asking how to extend a final class. It is asking why a class declared as final could possibly extend another class.


From this thread:

A final class is simply a class that can't be extended.

However, I have a helper class which I declared to be final and extends another class:

public final class PDFGenerator extends PdfPageEventHelper {
    private static Font font;

    private PDFGenerator() {
        // prevent instantiation
    }

    static {
        try {
            BaseFont baseFont = BaseFont.createFont(
                "/Trebuchet MS.ttf",
                BaseFont.WINANSI,
                BaseFont.EMBEDDED
            );

            font = new Font(baseFont, 9);

        } catch(DocumentException de) { 
            de.printStackTrace();

        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public static ByteArrayOutputStream generatePDF() throws DocumentException {            
        Document doc = new Document();
        ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();        
        PdfWriter pdfWriter = PdfWriter.getInstance(doc, baosPDF);

        try {           
            // create pdf

        } catch(DocumentException de) {
            baosPDF.reset();
            throw de;

        } finally {
            if(doc != null) {
                doc.close();
            }

            if(pdfWriter != null) {
                pdfWriter.close();
            }
        }

        return baosPDF;
    }
}

Eclipse does not detect anything wrong with it. I have tested the class and the PDF was successfully generated without error.

Why was I able to extend a final class when I should not be able to in theory?

(I am using Java 7 if that matters.)


Solution

  • A Class marked as final can extend another Class, however a final Class can not be extended.

    Here is an example:

    This is allowed

    public class Animal {
    
    }
    
    public final class Cat extends Animal {
    
    }
    

    This is not allowed

    public final class Animal {
    
    }
    
    public class Cat extends Animal {
    
    }