• Post Reply Bookmark Topic Watch Topic
  • New Topic

Constructors in Java  RSS feed

 
Max Ho
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I have two questions regarding Java constructors.

1. The first question is regarding no-argument constructors. I was reading this set of notes and was confused by this no-argument constructor created in the notes. In the code below, it created the public Point() no-arg constructor. However, it assigns 0 and both x and y. In this case, why isn't x and y referred to as this.x and this.y? And if x and y is referred to in this no-arg constructor, are they even valid?


http://www3.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInheritancePolymorphism.html



2. My second question is what is the correct way of creating multiple constructors? Some use this(x,y,z) while other use this.x, this.y in the body of the constructor.

Thank you!
 
Carey Brown
Saloon Keeper
Posts: 3310
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"this" is only necessary if there is a parameter with the same name. In the case of your constructor, the parameter named 'x' is presumed unless you qualify it with "this.x".

The use of "this(x,y,z)" allows you to build on top of another constructor without duplicating code. Whichever is cleaner and more readable and reduces redundant code.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is not a default constructor. Lots of people say default constructor but you only get a default constructor if you don't write a constructor at all.
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that explicitly initializing the instance int variables to 0 is redundant. Instance variables are implicitly initialized and ints are initialized to 0. The code would behave exactly the same if the no-arg Point() constructor had an empty body. That is, this has the same effect:

Note also that leaving out this constructor won't result in the same class getting a no-arg constructor by default if you leave in the one that has parameters.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But it is probably good style to initialise all instance methods in the constructor. It used to say that in the Java Tutorials. Even if the value is the same as the default values.
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:But it is probably good style to initialise all instance methods in the constructor. It used to say that in the Java Tutorials. Even if the value is the same as the default values.

I'm sure that's debatable. There are a few considerations: number of variables involved, verbosity of the code, consistency across the code base, to name a few.

If there are a non-trivial number of instance variables, do you explicitly initialize all of them? Can and will developers do that consistently throughout the program, for all classes? Does the additional noise in the code really add value? Is it worth the effort? What if you add a new instance variable and forget to update the constructor?
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take your point, Junilu. If you go through Effective Java™ by Bloch, almost on the first page he tells you how to use factory methods. If you use factory methods, then you are probably not going to initialise any fields in the constructor.
 
Max Ho
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Thanks for all your replies!

Just to probe further, where is a good place to learn best practices for java? Here I suppose - https://docs.oracle.com/javase/tutorial/ ?
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Effective Java by Joshua Bloch. We have reviews on our books pages.
 
Max Ho
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great, thank you!
 
salvin francis
Bartender
Posts: 1649
37
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:That is not a default constructor. Lots of people say default constructor but you only get a default constructor if you don't write a constructor at all.

This is actually news to me.

I always thought that any constructor without args was a 'default' constructor.

Some online tutorials too mention it in this manner: http://www.javatpoint.com/constructor

 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
salvin francis wrote:. . . Some online tutorials too . . .
You mean some online tutorials get it wrong, too
This is one of the instances where you can actually understand the Java® Language Specification which tells you what a default constructor is.
If a class contains no constructor declarations, then a default constructor is implicitly declared.
 
salvin francis
Bartender
Posts: 1649
37
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You mean some online tutorials get it wrong, too

Yes I meant that
 
Giovanni Montano
Ranch Hand
Posts: 428
7
Android Open BSD Slackware
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:That is not a default constructor. Lots of people say default constructor but you only get a default constructor if you don't write a constructor at all.


So is please the exact name "constructor without parameters"?
it is useful to know considering constructors are daily java bread.thanks
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would have thought the official name would be in the Java® Language Specification but I couldn't find it. I suspect the official name is “nullary constructor” which I think is a terrible name but I have't been able to confirm that. “Constructor without arguments” will do nicely, thank you
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I doubt "Constructor without arguments" will catch on. You just have to understand the nuance of "default" and "no-args". A no-args constructor has no arguments. A default constructor is one that the compiler provides when there is no explicit constructor in the code. Finally, the default constructor also happens to be a no-args constructor. ¯\_(ツ)_/¯
 
Tim Holloway
Saloon Keeper
Posts: 18789
74
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
salvin francis wrote:
Campbell Ritchie wrote:That is not a default constructor. Lots of people say default constructor but you only get a default constructor if you don't write a constructor at all.

This is actually news to me.

I always thought that any constructor without args was a 'default' constructor.

Some online tutorials too mention it in this manner: http://www.javatpoint.com/constructor



So do Sun's JavaDocs. Explicitly. Repeatedly.

The "default" constructor is what gets invoked if you create a Java object via the newInstance() method without providing any arguments. It is, not co-incidentally, also the constructor that bean factories - such as the one inside JPA/EJB will invoke for internally-constructed bean instances in the absence of more specialized functions. In fact, EVERY EJB/JPA object must have a no-arguments constructor and yes, the docs call it a default constructor because it must exist or the bean isn't spec-compliant (or functional!) no matter how many other constructors the bean may have or inherit.

You can argue that the no-args constructor is simply what its name says and that it has no more right to be called "default" than any other constructor, but many Java subsystems and mechanisms do depend on there being a default constructor, even if the user code itself doesn't.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a few things which are easy to understand in the Java® Language Specification. That section shows a Java® mechanism which depends on there not being a default constructor.
 
Tim Holloway
Saloon Keeper
Posts: 18789
74
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Incidentally, the use of "this" qualifiers for member methods and properties is sometimes mandated by shop standards as a consistent syntax that leaves no ambiguity in the possible event that the item in question might be accidentally overlaid in scope. Although IDEs are good at pointing out possible ambiguities, some shops don't wait for the IDE to do it.

Also, many automated code generators like to produce stuff like this:



Without the explicit qualification, this otherwise innocent-looking method would leave the instance property unset, since without a "final" on the method argument, changing argument variable values is legal in Java.

I also have a few constructors where I have code like so:



This is a little contrived (it assigns, then re-assigns x and y in the second constructor) but similar to stuff I do a lot of.

 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim Holloway wrote:
The "default" constructor is what gets invoked if you create a Java object via the newInstance() method without providing any arguments. It is, not co-incidentally, also the constructor that bean factories - such as the one inside JPA/EJB will invoke for internally-constructed bean instances in the absence of more specialized functions. In fact, EVERY EJB/JPA object must have a no-arguments constructor and yes, the docs call it a default constructor because it must exist or the bean isn't spec-compliant (or functional!) no matter how many other constructors the bean may have or inherit.

And this is where confusion can arise when these terms are used loosely.

(BTW, the Java Tutorials use the term "zero-argument constructor": https://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html -- and I just saw the term "nullary constructor" for the very first time, too )

Technically, it's the zero-argument constructor, which is not necessarily a default constructor, which is invoked. If you try calling newInstance() on a class that has only a constructor that does take arguments, you'll get an InstantiationException.
 
Tim Holloway
Saloon Keeper
Posts: 18789
74
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:

Technically, it's the zero-argument constructor, which is not necessarily a default constructor, which is invoked. If you try calling newInstance() on a class that has only a constructor that does take arguments, you'll get an InstantiationException.


True, but the JavaBean-based systems such as EJB don't permit that. They require a "nullary" constructor, which is the default used when no explicit arguments are supplied.

So it may not be a core java term, but it is very much a term used by some of the standard Java systems.
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

It's like this:

How many constructors does class Foo have? Answer: One constructor, which the compiler provides implicitly by default
How many arguments does the Foo constructor have? Answer: Zero arguments. The constructor that the compiler provides has zero arguments.
Does Foo have a zero-argument default constructor? Answer: Yes. See the above two answers.

How many constructors does class Bar have? Answer: One constructor, provided explicitly in the code.
Does Bar have a zero-argument constructor? Answer: Yes, obviously.
Is the Bar constructor a default constructor? Answer: No, because the compiler DID NOT have to provide it.

How many constructors does class Baz have? Answer: One constructor. It takes a single argument.
Does Baz have a zero-argument constructor? Answer: No. See for yourself.
Does Baz have a default constructor? Answer: No. The compiler only provides a default constructor if there are no explicit constructors.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim Holloway wrote:. . . I also have a few constructors where I have code like so: . . .
What's wrong with this sort of code?I presume that Foo() is a misspelling of Foo.
 
Tim Holloway
Saloon Keeper
Posts: 18789
74
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the problems I have with "All You Have To Do Is..." Syndrome is that even "Hello World" is more likely than not to take 20 minutes for me to cook up from scratch.

Actually, I was in an IT class in college where it took us 15 minutes to get all the mis-spellings, mis-capitalizations and other lint out of Hello World.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I meant using this() and super() in the different constructors. I swapped them round from what you posted.
 
Giovanni Montano
Ranch Hand
Posts: 428
7
Android Open BSD Slackware
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:I would have thought the official name would be in the Java® Language Specification but I couldn't find it. I suspect the official name is “nullary constructor” which I think is a terrible name but I have't been able to confirm that. “Constructor without arguments” will do nicely, thank you


In the american old west were the cowboys are numerous as NPE, the Sherif is the class and we could say the constructor the badge!

I am curious regarding the declarations

the ones really common to load up at the startup the arrays in a lot of MVC models patterns.
So these "static" without fields declararations( i mean for ex. as : static public final ciao() {}) in some ways are they connected with these constructor not declared?
or the VM does not consider these constructors if are not called with:
or my intuition is far from the reality in both the cases playing a trick, gringos?

 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This

is called a static initializer. It executes when the Class is initialized, before any constructor (which is connected with the instance). So no, they don't have anything to do with the constructor.
 
Giovanni Montano
Ranch Hand
Posts: 428
7
Android Open BSD Slackware
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:This

is called a static initializer. It executes when the Class is initialized, before any constructor (which is connected with the instance). So no, they don't have anything to do with the constructor.

Thanks Knute, do you know by any chance where can I find these kind of info( what happens when I play execute), I am really interested to know the order the JVM follow, to better understand java and android
 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This page might help. And you can alway write a quick program like this:



When run it gives you
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:This page might help. . . .
But that it s JLS link. We all know how hard the JLS can be to understand.

Nice bit of code, however
 
Giovanni Montano
Ranch Hand
Posts: 428
7
Android Open BSD Slackware
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Really cool Knute, thank you very much. And the link you gave me is an excellent starting point. Ritchie is right is not easy, but understanding these concepts really pay off imo, more than writing hallo world in malboge I guess! Every gain builds a stone. This forum is really cool because is one of the few place in the web that goes on the why and not on the how.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Giovanni Montano wrote:Really cool . . . This forum is really cool . . .
Thank you
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!