• Post Reply Bookmark Topic Watch Topic
  • New Topic

Constructors in extended classes  RSS feed

 
Biff Malone
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I have a class (AbcChild) that extends a superclass (AbcSuper), I can call a method on the "AbcChild.myMethod()" where "myMethod()" is not defined in AbcChild -- and the JVM will execute the "myMethod()" method definition that is in the superclass.
However, this is not the case with constructors. If I define a constructor "AbcSuper(String name)" in the superclass but do not define that same constructor in "AbcChild" but I try to instantiate an "AbcChild" with "AbcChild abc = new AbcChild(theName);" then I get a compile error.
Why are constructors not inheritable by extending classes?
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Biff,
Welcome to JavaRanch. Well constructors are not the same sort of animal that methods are and of course super class constructor names are different from their subclasses. They are used to allocate storage and initialize instance state. Methods are used for communication between object instances and in their case polymorphism plays a tremendous role in OO systems. Also, the compiler is implemented in such a way that if you don't call a super constructor, it assumes that you want to use the default (no args) super constructor, since it is always guaranteed to exist. You realize, of course that you can do the following:

That just means you have to code the child constructor yourself and explicitly call the correct super constructor.
 
Francis Siu
Ranch Hand
Posts: 867
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Biff
welcome
Michael said the truth that
if you don't call a super constructor, it assumes that you want to use the default (no args) super constructor, since it is always guaranteed to exist.
I think your a part of programme may be


In this case,the compiler can not find out the related constructor in AbcSuper because the parameter list in constructor does not match what the AbcChild called.
So,it gave you compiler error.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!