Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Siera/Bates, chapter 2. question #11

 
Rachel Glenn
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is the following correct...

1. When an instance of SubSubAlpha is created, the constructor for SubAlpha is not called because it is private. right ?
2. But the protected constructor of Alpha DOES get called because it is protected (therefore inheritied)?

Also, suppose SubAlpha contained a public member variable, like int x. Would that member variable be inherited by SubSubAlpha?
 
Praveen Kumar M K
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could you please post the question in full, I dont have the book
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rachel,


You need to understand few concepts. first of all constructors are not inherited. the members of class instance or static members are inherited. Constructors are for Object Initialization so there is no inheritance.

Secondly when you make an object of a class with new operator for e.g say i have a class structure like this

class B
{

}

class A extends B
{

}

now if i do new A(); what will happen ? it will call constructor of A(in this case since i have not typed a constructor it will call compiler supplied default no-arg constructor). now the first call in this constructor will be of super() which will call B's default constructor which again have a super class which will ultimately call Object class constructor. Now SubAlpha has a private constructor , which means you cannot create object of this class from OUTSIDE of this class. if you do you will get compile time error. the question creates object of SubSubAlpha like new SubSubAlpha(); now SubSubAlpha extends Alpha and NOT SubAlpha. had SubSubAlpha extends SubAlpha then you would get a compile time error.


in short the answers to your question is that SubAlpha constructor is not called because we are not calling it i.e the program is not calling it. and the protected constructor of Alpha is called because SubSubAlpha extends Alpha and we are creating object of SubSubAlpha which calls constructor of Alpha.

also keep in mind constructor of Alpha has a protected access, so it will be called from only from the classes which extends Alpha.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic