• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in constructor

 
Edmen Tay
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, this question from Enthuware SCJP5 Mock Test. I had tried the code in IDE below,



I hit compile error at line 10, then I explicitly declare constructor "SuperClass(){}" in SuperClass. It work fine.

Is it because of explicit declare of constructor with parameter argument in super class will need to declare constructor with no argument as well?

Can anyone help?

Many Thanks.

Edmen
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Edmen, the compiler will declare a default constructor only if the programmer hasnt provided one.
But in this case,


There is already a constructor, so you will have to add a default constructor.

Hope this helps.
 
Anthony Accioly
Greenhorn
Posts: 18
IntelliJ IDE Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it because of explicit declare of constructor with parameter argument in super class will need to declare constructor with no argument as well?


Exactely. The compiler only automagicaly inserts a non argument constructor in a class when no other constructor is present. And sub class constructors without a explicity call to a super class constructor will have a call to a non argument super class constructor automagicaly inserted
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya you are right. Compiler is adding super() call in your second constructor.

SubClass(int i, int j){//line 10, compile error
super();
}
 
Edmen Tay
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I got it. Thanks for the prompt reply.

Edmen
 
Himanshu Gupta
Ranch Hand
Posts: 598
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it is because of the explicit constructor declared in your SuperClass. In your sub class the first line should call either some constructor of the same class or constructor of super class.

The rules are :

  • Before creation of any Object its super class constructor and its constructor should always run.
  • The first statement in constructor should be a call to this or super.



  • ------------------------------------------------------------------

  • If you want to call constructor of the same class then use this keyword.

  • Like here you can use this(i);


    This will compile. Reason is constructor SubClass(int i) is calling super. So the rule is not broken.
  • You can call super class constructor using super keyword. The code will be






  • HTH
    [ December 29, 2008: Message edited by: Himanshu Gupta ]
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic