码迷,mamicode.com
首页 > 其他好文 > 详细

Writing Final Classes and Methods

时间:2015-06-16 01:16:18      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

 

You can declare some or all of a class‘s methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Objectclass does this—a number of its methods are final.

You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. For example, you might want to make thegetFirstPlayer method in this ChessAlgorithm class final:

class ChessAlgorithm {
    enum ChessPlayer { WHITE, BLACK }
    ...
    final ChessPlayer getFirstPlayer() {
        return ChessPlayer.WHITE;
    }
    ...
}

Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.

Note that you can also declare an entire class final. A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like theString class.

Writing Final Classes and Methods

标签:

原文地址:http://www.cnblogs.com/hephec/p/4579566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!