In this program new keyword is used in a SetCredits() method to hide similar method in the base class.
If you change ScholarshipStudent freeStudent = new ScholarshipStudent();
into
Student freeStudent = new ScholarshipStudent(); the output is
/*
Megan's tuition is $836.25
Luke's tuition is $836.25
*/
How can this be explained?
using System;
class DemoStudents
{
public static void Main()
{
Student payingStudent = new Student();
ScholarshipStudent freeStudent = new ScholarshipStudent();
payingStudent.SetName("Megan");
payingStudent.SetCredits(15);
freeStudent.SetName("Luke");
freeStudent.SetCredits(15);
Console.WriteLine("{0}'s tuition is {1}", payingStudent.GetName(), payingStudent.GetTuition().ToString("C"));
Console.WriteLine("{0}'s tuition is {1}",
freeStudent.GetName(),
freeStudent.GetTuition().ToString("C"));
Console.ReadKey();
}
}
class Student
{
private const double RATE = 55.75;
private string name;
protected int credits;
protected double tuition;
public string GetName()
{
return name;
}
public void SetName(string name)
{
this.name = name;
}
public void SetCredits(int creditHours)//SetCredits method in the child class as well
{
credits = creditHours;
tuition = credits * RATE;
}
public double GetTuition()//no SetTuition() method
{
return tuition;
}
}
class ScholarshipStudent : Student
{
public new void SetCredits(int creditHours) //polymorphism
{
credits = creditHours;
tuition = 0;
}
}
/*
Megan's tuition is $836.25
Luke's tuition is $0.00
*/