`

认识final修饰符

    博客分类:
  • Java
 
阅读更多
1. 对于类
Occasionally, you want to prevent someone from forming a subclass from one of your classes. Classes that cannot be extended are called final classes, and you use the final modifier in the definition of the class to indicate this. For example, let us suppose we want to prevent others from subclassing the Executive class. Then, we simply declare the class by using the final modifier as follows:

final class Executive extends Manager
{
   . . .
}

2. 对于类中的方法
You can also make a specific method in a class final. If you do this, then no subclass can override that method. (All methods in a final class are automatically final.) For example,

class Employee
{
   . . .
   public final String getName()
   {
      return name;
   }
   . . .
}

Note: Recall that fields can also be declared as final. A final field cannot be changed after the object has been constructed. However, if a class is declared as final, only the methods, not the fields, are automatically final.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics