Java Final Equivalent Keyword in C#
This tutorial will discuss the C# keywords equivalent to the final keyword in Java.
Java final
Keyword Equivalent in C
Unfortunately, there is no keyword in C# that does the same thing as the final
keyword in Java does. The final
keyword serves different purposes under different contexts. In class and function declaration, the final
keyword is used to prevent any inheritance from the class or any new definition of the virtual function. In the field initialization, the final
keyword specifies that the specific field value cannot be modified later on in the program.
Java final
Keyword in Class and Function Declaration
The sealed
keyword in C# is equivalent to the final
keyword in the Java language if it is used for class or function declaration. The following code example shows us how to use the final
keyword in Java’s class declaration.
public final class MyClass {...}
The above code prevents us from inheriting the MyClass
class in Java. This goal can be achieved with the sealed
keyword in C#. The following code example shows us how we can use the sealed
keyword in class declaration in C#.
public sealed class MyClass {...}
The above code prevents us from inheriting the MyClass
class in C#. The final
keyword also specifies that no there can be no more definitions of a virtual function in Java. The following code example shows us how we can use the final
keyword in a function declaration in Java.
public class MyClass
{
public final void myFunction() {...}
}
This prevents us from making any more definitions of the virtual function myFunction()
in Java. We can replicate this functionality with the sealed
and override
keywords in C#. The following code example shows us how we can use the sealed
keyword in a function declaration in C#.
public class MyClass : MyBaseClass
{
public sealed override void myFunction() {...}
}
The above code prevents us from making any more definitions of the virtual function myFunction()
in C#
Java final
Keyword in Field Initialization
The readonly
keyword in C# is equivalent to the final
keyword in the Java language if used for field initialization. The following code example shows us how we can use the final
keyword in Java’s field initialization.
public final float pi = 3.14;
This prevents us from changing the value of pi
in Java. This goal can be achieved with the readonly
keyword in C#. The following code example shows us how we can use the readonly
keyword in field initialization in C#.
public readonly float pi = 3.14;
This prevents us from changing the value of pi
in C#.