Preventing Extending and Overriding

Neither a final class nor a final method can be extended. A final data field is a constant. You may occasionally want to prevent classes from being extended. In such cases, use the final modifier to indicate that a class is final and cannot be a parent class. The Math class is a final class. The String, StringBuilder, and StringBuffer classes are also final classes. For example, the following class A is final and cannot be extended:

public final class A {
// Data fields, constructors, and methods omitted
}

You also can define a method to be final; a final method cannot be overridden by its subclasses.
For example, the following method m is final and cannot be overridden:

public class Test {
// Data fields, constructors, and methods omitted
public final void m() {
// Do something
}
}

The modifiers public, protected, private, static, abstract, and final are used on classes and class members (data and methods), except that the final modifier can also be used on local variables in a method. A final local variable is a constant inside a method.

原文链接:Preventing Extending and Overriding

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
Love begins with a smile, grows with a kiss and ends with a tear.
爱,起于微笑,浓于亲吻,逝于泪水
评论 抢沙发

请登录后发表评论

    暂无评论内容