C# sealed vs Java final

前端 未结 3 1390
滥情空心
滥情空心 2020-12-24 09:39

Would anybody please tell me as the reason the following use of sealed does not compile? Whereas, if I replace sealed with final and c

3条回答
  •  一向
    一向 (楼主)
    2020-12-24 10:10

    That's because final in Java means plenty of different things depending on where you use it whereas sealed in C# applies only to classes and inherited virtual members (methods, properties, events).

    In Java final can be applied to:

    • classes, which means that the class cannot be inherited. This is the equivalent of C#'s sealed.
    • methods, which means that the method cannot be overridden in a derived class. This is the default in C#, unless you declare a method as virtual and in a derived class this can be prevented for further derived classes with sealed again. That's why you see sealed members in C# a lot less than final members in Java.
    • fields and variables, which means that they can only be initialized once. For fields the equivalent in C# is readonly.

提交回复
热议问题