aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt in constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt in constructor" Watch "doubt in constructor" New topic
Author

doubt in constructor

Edmen Tay
Ranch Hand

Joined: Oct 21, 2008
Posts: 39
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

Joined: Sep 16, 2008
Posts: 509
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

Joined: Dec 22, 2008
Posts: 16

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

Joined: Oct 16, 2008
Posts: 952
Ya you are right. Compiler is adding super() call in your second constructor.

SubClass(int i, int j){//line 10, compile error
super();
}


SCJP 6
Edmen Tay
Ranch Hand

Joined: Oct 21, 2008
Posts: 39
Ok, I got it. Thanks for the prompt reply.

Edmen
Himanshu Gupta
Ranch Hand

Joined: Aug 18, 2008
Posts: 598

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 ]

    My Blog SCJP 5 SCWCD 5
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: doubt in constructor