Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C# - SEALED CLASS


Sealed Class


As the name suggests, a Sealed Class is a class that is sealed.


Well! In simple words a class marked as sealed cannot be inherited.


Example :



sealed class LivingBeing 
{
    public void breathe() 
    {
        System.Console.WriteLine("Breathes oxygen from Air");
    }
}

class Fish : LivingBeing 
{
    public void breathe() 
    {
        System.Console.WriteLine("Breathes oxygen from Water");
    }
}

class CreateLivingBeing
{
	public static void Main(string[] args)
	{
        Fish fish = new Fish();
	}
}


Output :



  error CS0509: 'Fish': cannot derive from sealed type 'LivingBeing'

So, in the above code, we have defined a sealed class LivingBeing,


sealed class LivingBeing
{
	public void breathe()
	{
		System.Console.WriteLine("Breathes oxygen from Air");
	}
}

And when we tried to inherit the LivingBeing class in Fish class,


class Fish : LivingBeing

We end up with the error,


error CS0509: 'Fish': cannot derive from sealed type 'LivingBeing'

Which actually says, you can't inherit from a sealed class.