• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

A question about Constructor

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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???
 
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Maulin.
 
Yeah, but how did the squirrel get in there? Was it because of the tiny ad?
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic