Page 1 of 1

About Question enthuware.ocajp.i.v7.2.1102 :

Posted: Sat Sep 24, 2016 2:11 pm
by matthewh86
Hello, I don't think this question is fully correct.

Under what situations does a class get a default constructor?
  • All classes in Java get a default constructor.
  • You have to define at least one constructor to get the default constructor.
  • If the class does not define any constructors explicitly.
  • All classes get default constructor from Object class.
  • None of the above.
The answer that was given as the correct answer was "If the class does not define any constructors explicitly."

I selected None of the above, because if a class extends another class without a no-args constructor, it does not get the default constructor.

Code: Select all

public class App {

	public App(int i) {

	}
	
	class SubApp extends App (){
		
	}

}
In this code snippet, SubApp does not define any constructors explicitly, but also does not seem to get the default constructor because App lacks a no-args constructor.

Have I misunderstood the question?

Re: About Question enthuware.ocajp.i.v7.2.1102 :

Posted: Sat Sep 24, 2016 8:41 pm
by admin
Whether a class gets the default constructor automatically or not has nothing to do with its super class. As the correct option says, if a class does not define any constructor explicitly, it will get the default constructor. That is the rule.

In your example as well, SubApp does get the default constructor. Why do you think it doesn't get it? Pay attention to the error message that you get when you compile your code.

-Paul.

Re: About Question enthuware.ocajp.i.v7.2.1102 :

Posted: Sun Sep 25, 2016 9:44 am
by matthewh86
Ok, thanks Paul. I was assuming that "get" meant "was able to compile".

The SubApp class gets a default constructor which then looks for a super no-args constructor, which it can't find.