Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Constructor in subclass only?  RSS feed

 
Varun Saini
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a query in the following code.
Can we skip the constructor in base class if we are providing it in derived class.

 
Campbell Ritchie
Marshal
Posts: 55681
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Please don't add new questions to an old thread, but start a new thread. Please use the code button; since you are new I have edited your post and you can see how much better it looks.

You need to check the basics about constructors:
  • 1: the compiler adds a default constructor if no other constructor has been written.
  • 2: A subclass constructor must call super(...) unless there is an accessible no-arguments constructor in the superclass.
  • 3: If there is no accessible constructor (including a default constructor) in the superclass, it is impossible to extend from that class.
  • Why don't you try that example?

    Your example is not very good. You have not explained why a ScienceBook should extend Book; why can't it simply be a Book? Why are you passing a title parameter and not using it.

    Why don't you explore the bytecode, like this?That will allow you to see whether there is a default constructor added by the compiler.

    By the way: In Java™ we say superclass and subclass, rather than base class and derived class.

     
    marc weber
    Sheriff
    Posts: 11343
    Java Mac Safari
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Varun Saini wrote:...will compiler provide a default constructor. Why??? ...

    Yes. If a class has no constructors explicitly provided, then the complier will insert a default constructor that takes no arguments. Similarly, if a constructor does not explicitly call "super" (or "this"), then the compiler will insert an implicit call to super (with no arguments) as the first line.

    In your example -- with the constructor Book(String title) and the call to super(title) both commented out -- the compiler will insert a no-args constructor in Book, which is implicitly called in the derived class constructor.

    This means that...

    ...is equivalent to...

     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!