C# sealed vs Java final

余生颓废 提交于 2019-11-30 03:44:17

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 potentially 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.
  • fields and variables, which means that they can only be initialized once. For fields the equivalent in C# is readonly.

Sealed in C# can be applied only to a reference types, and has impact on inheritance tree.

In practise the type marked as sealed guranteed to be the last "leaf" in the inheritance tree, or in short, you can not derive from the type declared like a sealed.

public sealed class Child : Base 
{
}

public class AnotherAgain : Child //THIS IS NOT ALLOWED
{
}

It can not be applied to a members.

Shedom Wei

Tigran's answer is not wrong while Joey's is a little incorrect.
Firstly you can look into this page: What is the equivalent of Java's final in C#?.
the sealed key word can apply to class,instance method and property but not variables, or interface's methods. Classes with sealed cannot be inherited. When sealed put on method, it must be by override in company. Every struct is sealed, so struct cannot be inherited. Check this image:


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!