Maha

Maha

  • NA
  • 0
  • 326k

virtual and override method

Oct 6 2012 12:47 AM
This example is given in the book. new keyword is used in derived class SetCredits() method to override similar method in base class. Code is highlighted.

Instead if we use virtual and override method output is similar. I wish to know whether it is correct to use virtual and override method. Intended alteration for the methods as follows:

Alteration in the Student class
public virtual void SetCredits(int creditHours)

Alteration in the ScholarshipStudent class
public override void SetCredits(int creditHours)

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
{
//SetCredits() method in the parent class as well
//This method overrides and hides its counterpart in the parent class.
new public void SetCredits(int creditHours)//polymorphism
{
credits = creditHours;
tuition = 0;
}
}
/*
Megan's tuition is $836.25
Luke's tuition is $0.00
*/


Answers (1)