• Post Reply Bookmark Topic Watch Topic
  • New Topic

Chapter 2: constructor (oca/ocp 7: k sierra & bert bates book) pg 134 & pg 137  RSS feed

 
Priyavrat Kumar
Greenhorn
Posts: 27
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why the above code compiles while the below code gives error ?
Both have overloaded constructor and first line with "this".
 
Knute Snortum
Sheriff
Posts: 4276
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The "this" here means "use the instance variable, not the parameter, called name".

The "this" here, with parentheses, calls a constructor with no parameters.

I didn't compile your code, but I imagine that the compiler sees that you have a circular reference between the two constructors.
 
Priyavrat Kumar
Greenhorn
Posts: 27
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first code i.e. Animal class, "super();" will be placed in which constructor and why not in the other one?
 
Vaibhav Sagar
Ranch Hand
Posts: 35
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Call to super will be placed in the Animal(String name) constructor. This is because we can't have a call to both super and this in the same constructor.
For e.g. what do you think would happen if the following was allowed?-


So your first example will be like this in terms of super/this calls-



This is called constructor chaining and eventually a constructor will need to call super(implicitly or explicitly), otherwise you'll get a exception like the one you got in your other example(because in other words that means the constructors are calling each other in a circular way).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!