17

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".

  • 26
    What if Person is a subtype of LivingThing ? You could write LivingThing lt = new Person(). Look for inheritance and interfaces. – xlecoustillier Feb 7 '15 at 19:55
  • 2
    Person Bob declares a variable of type "reference to Person" called Bob. new Person() creates a Person object. References, variables and objects are three different things! – immibis Feb 8 '15 at 1:48
  • 5
    Are you annoyed by the redundancy? Then why not write var bob = new Person();? – 200_success Feb 8 '15 at 18:19
  • 4
    Person Bob(); is possible in C++ and means nearly the same thing as Person Bob = Person(); – user60561 Feb 8 '15 at 18:34
  • 3
    @user60561 no, it declares a function taking no arguments and returning Person. – Nikolai Feb 9 '15 at 8:42
52

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();
  • 20
    This would be a lot clearer if you lower-cased your object names. – Lightness Races in Orbit Feb 8 '15 at 18:49
  • 38
    Good example of the specification; bad example of inheritance. To anyone else reading this, please, don't try to solve user roles using inheritance. – Aaronaught Feb 8 '15 at 19:01
  • 8
    @Aaronaught is correct. Don't create separate classes for different types of people. Use a bitfield enum. – Cole Johnson Feb 8 '15 at 19:42
  • 1
    @Aaronaught It's all very well saying what not to do, but it's not very helpful without saying what people should do instead. – Pharap Feb 8 '15 at 23:45
  • 5
    @Pharap: I have done exactly that, in several other questions. The simple answer is that users (authentication/identity) and security policy (authorization/permissions) should be treated as separate concerns, and the standard models for security policy are either role-based or claims-based. Inheritance is more useful to describe the object that actually does the authentication, e.g. an LDAP implementation and a SQL implementation. – Aaronaught Feb 9 '15 at 2:44
34

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.

  • 2
    +1: I will do the IPerson example in my code to ensure I do not accidentally use any private methods when I'm writing code that should be copy/pastable to another IPerson implementation. – Cort Ammon Feb 7 '15 at 21:22
  • @CortAmmon I think you have a typo there, clearly you meant "work with polymorphism" rather than copy/pastable on that code :D – Benjamin Gruenbaum Feb 8 '15 at 16:42
  • @BenjaminGruenbaum sure, for some definition of polymorphism ;-) – Cort Ammon Feb 8 '15 at 18:01
  • @CortAmmon how would you accidentally call a private method? Surely you meant internal? – Cole Johnson Feb 8 '15 at 19:43
  • @ColeJohnson either way. I wrote that thinking of a specific case that I run across where private is meaningful: factory methods that are part of the class being instantiated. In my situation, access to private values should be the exception, not the norm. I work on code which is going to long outlive me. If I do it this way, not only am I unlikely to use any private methods myself, but when the next developer copy/pastes this a few dozen places and the developer after that copies them, it decreases the odds that someone sees an opportunity to use private methods as "normal" behavior. – Cort Ammon Feb 8 '15 at 20:08
21
  1. 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.

  2. 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.

  3. 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>();
    
  4. In some languages you do your best to avoid stating the types of variables as in F#:

    let list123 = [ 1; 2; 3 ]
    
  • 5
    It's probably more accurate to say that your second example create a pointer to a new Bob object. The way things are stored is technically an implementation detail. – Robert Harvey Feb 7 '15 at 22:41
  • 4
    "The first to create a local object on the stack, the second to create an object on the heap." Oh man, not this misinformation again. – Lightness Races in Orbit Feb 8 '15 at 18:50
  • @LightnessRacesinOrbit better? – AK_ Feb 8 '15 at 21:09
  • 1
    @AK_ While "dynamic" pretty much means "heap" (when heap is the memory model used by the platform), "automatic" is very distinct from "stack." If you do new std::pair<int, char>(), then the members first and second of the pair have automatic storage duration, but they are probably allocated on the heap (as members of the dynamic-storage-duration pair object). – Angew Feb 9 '15 at 10:06
  • 1
    @AK_: Yes, those names imply precisely what they mean, whereas this "stack" vs "heap" nonsense does not. That's the entire point. That you find them confusing only reinforces the need for us to teach them, so that you are not relying on inaccurate/incorrect terminology just because it's familiar! – Lightness Races in Orbit Feb 9 '15 at 10:29
3

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.

1

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();
  • BTW the Java language sets a strong convention for using lower case identifier names, like bob, not Bob. This avoids a lot of ambiguity e.g. package.Class vs. Class.variable. – Jerry101 Feb 7 '15 at 20:11
  • ...and that's why you have clazz. – a CVn Feb 8 '15 at 20:47
  • No, clazz is used because class is a keyword so it can't be used as an identifier. – Jerry101 Feb 8 '15 at 21:00
  • ...which wouldn't be a problem if naming conventions weren't as they are. Class is a perfectly valid identifier. – cHao Feb 9 '15 at 1:03
  • ...as are cLaSs, cLASS and cLASs. – el.pescado Feb 9 '15 at 8:35
1

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!)

  • Regarding books, both my C# book and Java book were from Joyce Farrell. That's just what the course specified. I've also been supplementing both with various youtube videos on C# and Java. – Jason Wohlgemuth Feb 7 '15 at 20:51
  • I wasn't criticising, just giving a reference to where this came from :) – David Scholefield Feb 7 '15 at 20:54

protected by gnat Feb 9 '15 at 8:58

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.