• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors in Inheritance

 
Jos� Alberto Mu�iz Navarro
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens when a new class extends from another. Is the constructor kept? I was solving a mock exam and it came up with something like:
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructors are called in order, base constructor first. So every B object first constructs an A object.
 
Junilu Lacar
Bartender
Pie
Posts: 7806
62
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructors in Java are not inherited although it may appear so when the compiler adds a default no-args constructor into a class that has no explicitly declared constructor. With a little experimentation (see code below) you will quickly see that constructors are not inherited.



Now see if you can figure out why GrandChild2 will not compile.
(Hint: by default, the compiler will insert a call to super() as the first statement in a constructor))

[ July 02, 2004: Message edited by: Junilu Lacar ]
(darned UBB )
[ July 02, 2004: Message edited by: Junilu Lacar ]
 
Jos� Alberto Mu�iz Navarro
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh I get it now.. so in order for it to compile I'd have to add a super(i) (where i is an int) in order for it to work =)

Thank you.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic