• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

super & Abstract class

 
Himanshu Jhamb
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.
I am having problems with the following code...
---------------------------------------------------
public class Base {
Base() {
System.out.println("In Base Class no args Constructor");
}
Base(int i) {
System.out.println("In Base Class one arg Constructor");
}
public abstract class AbsDerived extends Base {
void myFunc();
}
public class Derived extends AbsDerived {
public Derived() {
super(); // Line 1
}

public Derived(int i) {
super(1) // Line 2
}
void myFunc() {
System.out.println("I do nothing");
}
}
---------------------------------------------
The problem is ... Line 2 gives a compiler error. It says that there is no matching constructor in class AbsDerived.
However, if we comment out line 2, the code compiles fine & when class Derived is instantiated, it correctly calls the Base Class's no argument constructor.
Why do we have problems with compiling super with arguments... ??
Please help...
thanks
- Himanshu
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructors are not inherited.
If you want to make both of your constructors in class Base available to Derived you have to declare the same constructors in AbsDerived which call super() with the appropriate arguments.

this way it works... You cannot invoke directly the constructor of Base from within Derived... you have to go through AbsDerived and the only way to do it is to declare the same-signature constructors in AbsDerived
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
Himanshu Jhamb
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the quick reply.. Valentin, that helps.
Have one more question, if I have constructor in an abstract class, isn't it like instantiating the abstract class ??
Maybe not, because we will always do a new on the Derived class, never on the AbsDerived class, correct ?
Please comment.
thanks.
Himanshu
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that's right. The fact of having a constructor in your abstract class doesn't mean you can instantiate the abstract class directly. Such a constructor is useful for setting up proprietary things of your abstract class, but the actual instantiation of the abstract class is done by instantiating a concrete class that extends your abstract class.
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic