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
328.1k
Override & new keyword
Jan 10 2012 3:32 PM
I wish to know different between using the
new
and the
override
keyword in this program. Because both are giving same results in following program. Even though it is said that Tostring() overrides the Object class version. You can notice in this text there is an override word but in the example program
new
is used.
Also when
return
keyword is used in the method header, indicates the type of return. But in this program in the method header type is
string
, return is combination of string and integer. Please explain the reason.
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);
Console.WriteLine(payingStudent.ToString());
Console.WriteLine(freeStudent.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
string
ToString() //Tostring() overrides the Object class version.
{
string stuString = "Student " + name + " has " + credits + " credits";
return stuString;
//OR
//return String.Format("Student {0} has {1} credits", name, credits);
}
}
class ScholarshipStudent : Student
{
new public void SetCredits(int creditHours)
{
credits = creditHours;
}
}
/*
Student Megan has 15 credits
Student Luke has 15 credits
*/
Reply
Answers (
38
)
How to validate numbers
Virtual Keywords