Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# sealed vs Java final

Tags:

java

c#

sealed

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

private sealed int compInt = 100;
public bool check(int someInt)
{
    if (someInt > compInt)
    {
        return true;
    }
    return false;
}
like image 455
Saurabh Ghorpade Avatar asked Apr 16 '12 08:04

Saurabh Ghorpade


3 Answers

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.
like image 144
Joey Avatar answered Sep 29 '22 06:09

Joey


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.

like image 22
Tigran Avatar answered Sep 29 '22 07:09

Tigran


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: sealed usage

like image 23
Sheldon Wei Avatar answered Sep 29 '22 07:09

Sheldon Wei