Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question about Constructor

 
XinJi Chang
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

While compiling,I got a error which says "Q7_2.java:9: Q7_1(int) in Q7_1 cannot be applied to ()"...
And after add "public Q7_1(){}" to line 3,it works....
But I dont't understand,there is no "Q7_2(){}" constructor in class Q7_2,
why i have to add "Q7_1" to class Q7_1???
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi XinJi
Okay..when we have 'extends' relationship then we would need someway to initialize the parents data (as its a part of child by inheritance) , right?
Now, what are our options? (only one)
1. Calling parent's constructor from child
Also, we must make sure that all the parent data get initialized first before the child data can get initialized (as per the initialization rules)..
How doesn't the JVM does it? It has to call parent's constructor. Which constructor it can call if the code doesn't have EXPLICITLY called any of the parent's constructor? Ans: Calling super() (no-arg constructor of parent).
Now, at this point you would see that in your case the JVM calls Q7_1's no-arg constructor from Q7_2(int i) {} and if you comment Q7_1() then it will not find it and throw compilation error.
Also, to make things more clear,
by default compiler puts 'default no-arg' constructor in the class if there is not "any" kind of constructor but if you have then it doesn't put no-arg constructor which is what is the case in Q7_1 class. It does have some constructor and so compiler automatically doesn't put Q7_1() {} automatically. If you remove Q7_1(int i) {} then it would work even without explicitly having Q7_1() {}
I hope I didn't confuse you.
Regards
Maulin
 
XinJi Chang
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Maulin.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic