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”.
8
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();
7
Let’s take your first line of code and examine it.
Person Bob = new Person();
The first Person
is a type specification. In C#, we can dispense with this by simply saying
var Bob = new Person();
and the compiler will infer the type of the variable Bob from the constructor call Person()
.
But you might want to write something like this:
IPerson Bob = new Person();
Where you’re not fulfilling the entire API contract of Person, but only the contract specified by the interface IPerson
.
6
-
This syntax is pretty much a legacy from C++, which, by the way, has both:
Person Bob;
and
Person *bob = new Bob();
The first to create an object within the current scope, the second to create a pointer to a dynamic object.
-
You definitely can have
something_else Bob = new Person()
IEnumerable<int> nums = new List<int>(){1,2,3,4}
You are doing two different thing here, stating the type of the local variable
nums
and you say you want to create a new object of the type ‘List’ and put it there. -
C# kind of agrees with you, because most of the time the type of the variable is identical to what you put in it hence:
var nums = new List<int>();
-
In some languages you do your best to avoid stating the types of variables as in F#:
let list123 = [ 1; 2; 3 ]
7
There is a huge difference between int x
and Person bob
.
An int
is an int
is an int
and it must always be an int
and can never be
anything other than an int
.
Even if you don’t initialize the int
when you declare it (int x;
),
it is still an int
set to the default value.
When you declare Person bob
, however, there’s a great deal of flexibility
as to what the name bob
might actually refer to at any given time.
It could refer to a Person
, or it could refer to some other class, e.g. Programmer
,
derived from Person
; it could even be null
, referring to no object at all.
For example:
Person bob = null;
Person carol = new Person();
Person ted = new Programmer();
Person alice = personFactory.functionThatReturnsSomeKindOfPersonOrNull();
The language designers certainly could have made an alternative syntax that would
have accomplished the same thing as Person carol = new Person()
in fewer symbols,
but they still would have had to allow Person carol = new Person()
(or make some strange rule making that particular one of the four examples above illegal). They were more concerned with keeping the language “simple” than in writing
extremely concise code.
That may have influenced their decision not to provide the shorter alternative syntax,
but in any case, it wasn’t necessary and they didn’t provide it.
The two declarations can be different but are often the same. A common, recommended pattern in Java looks like:
List<String> list = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
These variables list
and map
are declared using the interfaces List
and Map
while the code instantiates specific implementations. This way, the rest of the code only depends on the interfaces and it’s easy to pick a different implementation classes to instantiate, like TreeMap
, since the rest of the code can’t depend on any part of the HashMap
API that’s outside the Map
interface.
Another example where the two types differ is in a factory method that picks a specific subclass to instantiate, then returns it as the base type so the caller needn’t be aware of the implementation details, eg a “policy” choice.
Type inference can fix the source code redundancy. Eg in Java
List<String> listOne = Collections.emptyList();
will construct the right kind of List thanks to type inference and the declaration
static <T> List<T> emptyList();
In some languages, type inference goes further, eg in C++
auto p = new Person();
5
In layman’s words:
- Separating declaration from instantiation helps decouple who uses the objects from who creates them
- When you do that, polyporphism is enabled since, as long as the instantiated type is a subtype of the declaration type, all code using the variable will work
- In strongly typed languages you must declare a variable stating its type, by doing simply
var = new Process()
you are not declaring the variable first.
0
It’s also about the level of control over what is happening. If the declaration of an object/variable automatically calls a constructor, for example, if
Person somePerson;
was automatically the same as
Person somePerson = new Person(blah, blah..);
then you’d never be able to use (for example) static factory methods to instantiate objects rather than default constructors, that is, there are times when you don’t want to call a constructor for a new object instance.
This example is explained in Joshua Bloch’s Effective Java (Item 1 ironically enough!)
2