是否可以在Java中扩展最终类? [英] Is it possible to extend a final class in Java?

查看:64
本文介绍了是否可以在Java中扩展最终类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于可能的重复项:

该线程没有要求如何扩展 final 类.在问为什么声明为 final 的类可能会扩展另一个类.

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.


来自线程:

final 类只是无法扩展的类.

但是,我有一个帮助程序类,该类声明为 final ,并 extends 另一个类:

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不会检测到任何错误.我已经测试了该类,并且PDF正确无误地成功生成了.

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

为什么在理论上我不应该能够扩展 final 类?

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

(如果重要的话,我正在使用Java 7.)

(I am using Java 7 if that matters.)

推荐答案

标记为 final Class 可以扩展另一个 Class ,但是最终课程不能扩展.

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

这里是一个例子:

允许

public class Animal {

}

public final class Cat extends Animal {

}

不允许

This is not allowed

public final class Animal {

}

public class Cat extends Animal {

}

这篇关于是否可以在Java中扩展最终类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆