TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Maha
NA
0
326.4k
method with new keyword
Oct 7 2012 9:27 AM
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
*/
Reply
Answers (
5
)
How do I parse XML from a serial port without using files?
Merge Same Data Column in DataGridView windows C#