Why to use Sealed Class ?
Where Sealed Classes are used ?
I have been ever wondered and hesitate to make a practice of using “sealed” keyword with each and every class other than un-sealed type (except classes that is to be inherit/derived). I went through many articles, blogs, and tips and found diverse view on regular usage of “sealed” type.Some advocate for using it for –1) It speeds as it JIT compiler works efficiently with non-virtual methods.2) It prevent future coming problem by restricting inheritance for those classes that are not meant for derived. A compile time checking and error is generated for type-safety. This advocate “Always declare a new class as sealed …”3) Type safety: by not allowing sealed classes to be generic type constraints/arguments.(I understand it through Static Class. Static classes are abstract and sealed by virtue. Abstract stop instantiation and sealed stops inheritance so this can't be used as generic type-constraints. I googled it to confirm and found correct ref: http://www.ruchitsurati.net/index.php/2010/07/07/sealed-classes-as-generic-constraints/)Some suggests for not using “sealed” unless it is very much required :1) It doesn't so much make efficient and can't easily noticed, so need to bother about speed of JIT.2) It makes burden on programmer.More points to note with respect to “sealed” class:
· A sealed class can't be a base class for other class. รจ So sealed class can't be an “abstract” class.· Sealed method should be avoided for just stopping override. We can use “virtual” keyword for this purpose.· An overridden method can be “sealed” and thus it will fix this version as a final and no further overriding can be done.· Sealed can be used to prevent extension of existing classes so that outsiders/third person can't extend the functionality using our class.· Modifier abstract can't used with a “sealed” class.(Structs are implicitly “sealed” hence they can't be inherited.)· Common methods, utility methods can be written in a sealed class?
Mahesh's has also explained "Why Sealed Classes?"Please comment/put your views.Thanks for reading
0 comments :
Post a Comment