Friday, March 13, 2015

C# vs Java : Preventing A Class From Being Inherited

To prevent a class from being inherited, in Java you use the final keyword:
public final class SuperClass {
}
public class SubClass extends SuperClass { // compiler error: cannot inherit from final class
   public static void main(String[] args) {
      System.out.println("Hello World");
      System.console().readLine();
   }
}
In C# you use the sealed keyword...
sealed class BaseClass {
}
 
class DerivedClass : BaseClass { // compiler error: cannot derive from sealed type
   public static void Main() {
      Console.WriteLine("Press Enter to continue...");
      Console.ReadLine();
   }
}

No comments:

Post a Comment