C# Object Creation of Inherited Class


A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.

The derived class inherits the base class member variables and member methods. Therefore, the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list.

Here you can see object is created for the inherited class.

Example

 Live Demo

using System;
namespace Demo {
   class Rectangle {
      protected double length;
      protected double width;
      public Rectangle(double l, double w) {
         length = l;
         width = w;
      }
      public double GetArea() {
         return length * width;
      }
      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }
   class Tabletop : Rectangle {
      private double cost;
      public Tabletop(double l, double w) : base(l, w) { }
      public double GetCost() {
         double cost;
         cost = GetArea() * 70;
         return cost;
      }
      public void Display() {
         base.Display();
         Console.WriteLine("Cost: {0}", GetCost());
      }
   }
   class ExecuteRectangle {
      static void Main(string[] args) {
         Tabletop t = new Tabletop(3, 8);
         t.Display();
         Console.ReadLine();
      }
   }
}

Output

Length: 3
Width: 8
Area: 24
Cost: 1680

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements