是否可以在Java中扩展最终类?

编程入门 行业动态 更新时间:2024-10-18 21:16:40
本文介绍了是否可以在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中扩展最终类?

本文发布于:2023-08-01 12:37:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1268432.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!