When will we create this type of object in C # ...?
I have seen the following type of script on some websites. Can anyone help me when we use this type of script exactly ...?
class emp
{
public void add()
{
MessageBox.Show("Emp class");
}
}
class dept : emp
{
public void disp()
{
MessageBox.Show("dept class");
}
}
emp ee = new dept();
I just want to know when we create this type of object emp 'ee = new dept ()' instead of 'emp ee = new emp ()' thanks shiva
a source to share
The above example demonstrates inheritance. Inheritance is an "IS A" relationship, in this case "dept" IS "emp", which means that anytime your code uses emp, it must also be able to use the dept object.
The assignment of the new division ee demonstrates that the dept is emp, although it can add additional functionality such as the disp method.
a source to share
The process shown here is called Inheritance.
Basically what is done is that the type of the variable is ee
declared as a type emp
; this is legal because type dept
has a relation to aa emp
(to say it out loud, "dept is type emp").
This can be done if you want to accept any variable that inherits from emp (as indicated by the declaration class dept : emp
) as a parameter of some type.
a source to share
Do you mean inheritance? If this is what you are asking for, you need to get a book on Object Oriented Programming in C #.
There is no reason for the disp () method in dept. You can just go:
emp ee = new dept (); ee.add ();
This will call the add () method on emp.
a source to share
We do this for runtime polymorphism. When we need to call a method of a derived class, but the called derived class needs to be called depends on the runtime based on user input. This is a very simple example:
static void Main(string[] args)
{
List<Shape> shapes = new List<Shape>();
shapes.Add(new Circle());
shapes.Add(new Square());
shapes.Add(new Rectangle());
foreach (Shape s in shapes)
s.Draw();
Console.Read();
}
public class Shape
{
public virtual void Draw() { }
}
public class Square : Shape
{
public override void Draw()
{
// Code to draw square
Console.WriteLine("Drawing a square");
}
}
public class Circle : Shape
{
public override void Draw()
{
// Code to draw circle
Console.WriteLine("Drawing a circle");
}
}
public class Rectangle : Shape
{
public override void Draw()
{
// Code to draw circle
Console.WriteLine("Drawing a rectangle");
}
}
*****Output:
Drawing a circle
Drawing a square
Drawing a rectangle*****
In a practical scenario, it is possible that the user determines at run time what shape he wants to draw. So on implementation, you create an object of class Shape and assign it a circle, rectangle or square depending on the user's choice (in a radio button or if-else). And when you call Shape.Draw (), it calls the corresponding method of the derived class.
a source to share