I hope to run the below C# codes to practice usage of abstract / sealed classes :
using System;
abstract class Person
// abstract : can be inherited but can't be instantiated
{
public Person()
{
Console.Write(this + " : ");
}
}
sealed class MichaelJackson : Person
// sealed : can't be inherited but can be instantiated
{
public void Say()
{
Console.WriteLine("Billie Jean is not my lover.");
}
}
class BilleJean : MichaelJackson
// An error will occurs because it tries to inherit a sealed class
{
public void Say()
{
Console.WriteLine("You are the one.");
}
}
class MainClass
{
static void Main(string[] args)
{
try
{
new Person();
// An error will occurs because it tries to be instantiated as an abstract class
}
catch (Exception e)
{
Console.WriteLine("Abstract class can't be instantiated.");
}
new MichaelJackson().Say();
try
{
new BilleJean().Say();
}
catch (Exception e)
{
Console.WriteLine("MichaelJackson : The kid is not my son");
}
}
}
As you know, the abstract class Person
can't be instantiated directly and also the sealed class MichaelJackson
can't be inherited by the other class BillieJean
.
I mean to get the result like the following, but the codes don't run although I've added try~catch
statement.
Abstract class can't be instantiated.
MichaelJackson : Billie Jean is not my lover.
MichaelJackson : The kid is not my son.
How can I solve this problem?
You are confusing compiling errors and runtime exceptions.
Trying to inherit a sealed class will produce a compiling error. This means that no executable will be created and that you will not be able to run your code.
A try-catch statement catches exceptions at runtime. E.g., it may catch a "division by 0" exception, but it can not catch a syntax error or a logical error the compiler is complaining about.
The term “runtime” refers to when the code is running. It means that the compiler successfully created an executable file and that you could start it. The compiler can compile successfully when there are warnings (green squiggly lines), code issues or hints (blue squiggly lines), but not when there are errors (red squiggly lines).