Find the output of C#.Net programs | Method Overriding | Set 3: Enhance the knowledge of C#.Net Method Overriding concepts by solving and finding the output of some C#.Net programs.
Question 1:
using System;
namespace Demo
{
abstract class Parent
{
public abstract void Print();
public abstract void PrintHello()
{
Console.WriteLine("Hello World");
}
}
class Child:Parent
{
public override void Print()
{
Console.WriteLine("Child class Method called");
}
}
class Program
{
//Entry point of the program
static void Main(string[] args)
{
Parent P = new Child();
P.Print();
P.PrintHello();
}
}
}
Question 2:
using System;
namespace Demo
{
abstract class Parent
{
public abstract void Print();
}
abstract class Child:Parent
{
public override void Print()
{
Console.WriteLine("Child class Method called");
}
}
class Program
{
//Entry point of the program
static void Main(string[] args)
{
Parent P = new Child();
P.Print();
}
}
}
Question 3:
using System;
namespace Demo
{
abstract class Parent
{
public static abstract void Print();
}
class Child:Parent
{
public static override void Print()
{
Console.WriteLine("Child class Method called");
}
}
class Program
{
//Entry point of the program
static void Main(string[] args)
{
Parent.Print();
}
}
}
Question 4:
using System;
namespace Demo
{
abstract class Parent
{
public abstract void Print();
}
class Child:Parent
{
public override void Print()
{
Console.WriteLine("Child class Method called");
}
}
class Program
{
//Entry point of the program
static void Main(string[] args)
{
new Child().Print();
}
}
}
Answer 1:
Output:
Explanation:
The above program will generate compile-time errors. Because we cannot define the abstract method in the base class, we can only declare an abstract method, and then that can be overridden in the derived class.
Answer 2:
Output:
Explanation:
The above program will generate syntax error because we cannot create the object of an abstract class.
Answer 3:
Output:
Explanation:
The above program will generate syntax errors because Print() is a static method, but the static method cannot be marked as an override, virtual, or abstract.
Answer 4:
Output:
Explanation:
In the above program, we created three classes Parent, Child, and Program. Here, Program is an abstract class that contains an abstract method Print(). Then we inherited Parent class into the Child class and override the Print() method.
Now look to the Main() method,
new Child().Print();
Here, we called the Print() method using the anonymous object of child class then the message "Child class Method called" will be printed on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer