是否可以在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 {
}