Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard

Question 98

Question ID: UKOCP31328


Given code:


And below statements:

1. Users of Event class will not be able to create an instance of Event class with null name

2. Users of Event class will not be able to create an instance of Event class with age = 100

3. name of Event class's instance can be changed later

4. age of Event class's instance can be changed later


How many of the above statements are correct?

  • A Only one statement
  • B Only two statements
  • C Only three statements
  • D All four statements
  • E None of the given statements
Reveal correct answer

Correct answer: E

Explanation

UKOCP31328:

Variable 'name' and 'age' are private and values are assigned to these variables in constructor only. No setters have been provided, hence after Event class's instance is created, name and age fields cannot be changed.


Constructor over here invokes the overridable validateAge(int) and normalizeName(String) methods. Malicious users can create the sub-class of Event and override validateAge(int) and normalizeName(String) methods, therefore allowing invalid values to be set in name and age fields. Hence, it is very much possible to create an instance of Event class with null name or with age = 100.

Hence, none of the given statements are correct.


To resolve this issue:

Create Event class with final modifier

or

Add final modifier to validateAge(int) and normalizeName(String) methods

or

Change modifier of validateAge(int) and normalizeName(String) methods to private


Check below link and section:

https://www.oracle.com/java/technologies/javase/seccodeguide.html

Guideline 7-4 / OBJECT-4: Prevent constructors from calling methods that can be overridden

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need