This example is given in the following website http://www.c-sharpcorner.com/Forums/Thread/156771/. It is said that "override is polymorphic but new is not".
When we use new keyword the output is:
/*
Student Megan has 15 credits
Student Luke has 15 credits
Student
*/
When we use override keyword the output is:
/*
Student Megan has 15 credits
Student Luke has 15 credits
Student Megan has 15 credits
*/
The word polymorphism means "many forms". Here new and override taking many forms. How can be said that override is polymorphic but new is not. Problem is highlighted.
using System;
class DemoStudents4
{
public static void Main()
{
Student payingStudent = new Student();
ScholarshipStudent freeStudent = new ScholarshipStudent();
payingStudent.SetName("Megan");
payingStudent.SetCredits(15);
freeStudent.SetName("Luke");
freeStudent.SetCredits(15);
object obj = payingStudent;
Console.WriteLine(payingStudent.ToString());
Console.WriteLine(freeStudent.ToString());
Console.WriteLine(obj.ToString());
Console.ReadKey();
}
}
class Student
{
private string name;
protected int credits;
public void SetName(string name)
{
this.name = name;
}
public void SetCredits(int creditHours)//SetCredits in the child class as well
{
credits = creditHours;
}
public new/override string ToString() //Tostring() overrides the Object class version.
{
string stuString = "Student " + name + " has " + credits + " credits";
return stuString;
}
}
class ScholarshipStudent : Student
{
new public void SetCredits(int creditHours)
{
credits = creditHours;
}
}
Loading
VulpesPosted Oct 28, 2012, 3:57 PM
Base b = new Derived();
The declared type of 'b' is Base.
The type of the object is the actual type of object assigned to the variable which, in the above example, is Derived.
However, if the line had been:
Base b = new Base();
then the type of the object would, of course, be Base.
This is important in polymorphism because it's the type of the object (not the variable) which determines which version of the method/property gets called.
Posted Oct 28, 2012, 6:21 PM
Posted Oct 28, 2012, 3:41 PM
What is the difference between the type of the variable and the type of the object?
VulpesPosted Oct 28, 2012, 11:18 AM