Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 98
Question ID: UKOCP31328
Given code:
- package com.udayankhattry.ocp;
- public class Event {
- private String name;
- private int age;
- public Event(String name, int age) {
- this.name = normalizeName(name);
- this.age = validateAge(age);
- }
- public int validateAge(int age) {
- if (age < 10)
- throw new IllegalArgumentException("Too young");
- if (age > 90)
- throw new IllegalArgumentException("Too old");
- return age;
- }
- protected String normalizeName(String name) {
- if (name == null)
- throw new IllegalArgumentException("Name is null");
- if (name.isBlank() || name.isEmpty())
- throw new IllegalArgumentException("Name is blank");
- return name.trim().toUpperCase();
- }
- }
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.
