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.3k
Override and new keyword
Sep 6 2012 11:01 AM
This example is given in the following website
http://www.c-sharpcorner.com/Forums/Thread/156771/
. Following code is in the program.
new
keyword is in question.
public
new
string ToString() //Tostring() overrides the Object class version.
{
string stuString = "Student " + name + " has " + credits + " credits";
return stuString;
}
If use
new
keyword only without using
object
obj = payingStudent; why we do not get object version (
Student
and
ScholarshipStudent
). Because there is no
override
keyword to override object version. 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
string ToString()
{
string stuString = "Student " + name + " has " + credits + " credits";
return stuString;
}
}
class ScholarshipStudent : Student
{
new public void SetCredits(int creditHours)
{
credits = creditHours;
}
}
/*
Student Megan has 15 credits
Student Luke has 15 credits
Student
*/
Reply
Answers (
9
)
C# using linq to sql
Embedding MS Office on a Form