File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Siera/Bates,  chapter 2. question #11 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Siera/Bates,  chapter 2. question #11" Watch "Siera/Bates,  chapter 2. question #11" New topic

Siera/Bates, chapter 2. question #11

Rachel Glenn
Ranch Hand

Joined: Oct 24, 2012
Posts: 95
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

Joined: Jul 03, 2011
Posts: 256
Could you please post the question in full, I dont have the book
gurpeet singh
Ranch Hand

Joined: Apr 04, 2012
Posts: 924

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.
I agree. Here's the link:
subject: Siera/Bates, chapter 2. question #11
It's not a secret anymore!