I\'ve learned C# over the course of the past six months or so and am now delving
ID: 645916 • Letter: I
Question
I've learned C# over the course of the past six months or so and am now delving into Java. My question is about instance creation (in either language, really) and it's more of: I wonder why they did it that way. Take this example
Person Bob = new Person();
Is there a reason that the object is specified twice? Would there ever be a something_else Bob = new Person()?
It would seem if I were following on from convention it would be more like:
int XIsAnInt;
Person BobIsAPerson;
Or perhaps one of these:
Person() Bob;
new Person Bob;
new Person() Bob;
Bob = new Person();
I suppose I'm curious if there's a better answer than "that's just the way it is done".
Explanation / Answer
Would there ever be a something_else Bob = new Person()?
Yes, because of inheritance. If:
public class StackExchangeMember : Person {}
Then:
Person bob = new StackExchangeMember();
Person sam = new Person();
Bob is a person too, and by golly, he doesn't want to be treated differently than anyone else.
Further, we could endow Bob with super powers:
public interface IModerator { }
public class StackOverFlowModerator : StackExchangeMember, IModerator {}
IModerator bob = new StackOverFlowModerator();
And so, by golly, he won't stand for being treated any differently than any other moderator. And he likes to sneak around the forum to keep everyone in line while incognito:
StackExchangeMember bob = new StackOverFlowModerator();
Then when he finds some poor 1st poster, he throws off his cloak of invisibility and pounces.
((StackOverFlowModerator) bob).Smite(sam);
And then he can act all innocent and stuff afterwards:
((Person) bob).ImNotMeanIWasJustInstantiatedThatWay();
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.