I have a class named开发者_JAVA技巧 fdetails
and I do not want any other class to inherit from this class.
Can I set it to not being inherited by another class. I would like to get this done in the following 3 languages:
- Java
- VB.NET 3.5
- C# 3.5
java: final
vb: NotInheritable (NonOverrideable for properties)
c#: sealed
In Java use the final keyword:
public final class fdetails{
}
In C# use the sealed keyword:
public sealed class fdetails{
}
In VB.net use the NotInheritable keyword:
public notinheritable class fdetails
end class
In C# you use the sealed
keyword in order to prevent a class from being inherited.
In VB.NET you use the NotInheritable
keyword.
In Java you use the keyword final
.
In JAVA - use the final keyword:
public final class FDetails
In C# - the sealed keyword:
sealed class FDetails
In order to prevent a class in C# from being inherited, the keyword sealed is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class. Code below...
//C# Example
sealed class ClassA
{
public int x;
public int y;
}
No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible...
class DerivedClass : ClassA { } // Error
Same in Java and VB.net:
java: final
vb: NotInheritable (NonOverrideable for properties)
Alternatively to https://stackoverflow.com/a/4096427/5292885 answer, one can create the base class with private constructor to avoid inheritance (in C#, you get error like the class is inaccessible due to its protection level in case if you refer the base class)
For C#, it's the "sealed" keyword.
For Java, it's the "final" keyword.
精彩评论