RoR
RoR

Reputation: 16502

Inheritance Polymorphism Question

Person studentA = new Student();

Person is a base class Student is a sub class of Person.

Why would anyone use the line of code above for? Why don't you just do

Student studentA = new Student();

Upvotes: 0

Views: 127

Answers (2)

t3rse
t3rse

Reputation: 10124

Sometimes you want to refer to an object in a more general sense. Most people understand user interfaces so here is a basic example:

Suppose you have a screen where you want every control to be disabled until some sort of cue, ie. a user fills in some initial input. Your controls may be things like Textboxes, Comboboxes (dropdowns), or Buttons. A way you can refer to all of the above in one fell swoop is to treat them as Controls.

You might write code like:

foreach(Control c in MyForm.Controls)c.Enabled = false;

This is one example but as you start programming more you'll see this is a pretty basic part of your object oriented existence.

One place where you can see most object oriented base class libraries employ this technique is with I/O - all input and output libraries available. In the most abstract sense you'll have a Stream but when you look at the class hierarchy you'll see polymorphic variations of the Stream concept: a file stream, a network stream, and so on. Reading and writing stream implementations will be done with "Readers" and "Writers" respectively. Doing some basic programming tasks will get you a really nice feel for how useful this polymorphism is. For example, writing code that reads from a stream and then abstracting it so that it can apply to any implementation of Stream that it is handed.

One thing I always try to suggest to people is to study the built in libraries to see how framework designers and programmers employ techniques like this effectively for very practical day to day usage.

Upvotes: 2

Falmarri
Falmarri

Reputation: 48605

You really wouldn't ever do that. But what if you had a vector of Person, and want to specify that some of the Persons that you add are Students?

You should probably read up on inheritance and polymorphism. Your question shows that you really haven't had to much experience programming.

This is the first link I pulled off google. http://msdn.microsoft.com/en-us/library/27db6csx%28v=vs.80%29.aspx

Upvotes: 0

Related Questions