Challenge - 5 Problems
Private Data Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of accessing private data member directly
What will be the output of the following Java code?
Java
class Person { private String name = "Alice"; } public class Main { public static void main(String[] args) { Person p = new Person(); System.out.println(p.name); } }
Attempts:
2 left
π‘ Hint
Private members cannot be accessed directly outside their class.
β Incorrect
The field 'name' is private in class Person. Trying to access it directly from Main causes a compilation error.
β Predict Output
intermediate2:00remaining
Output when accessing private member via getter
What will be the output of this Java program?
Java
class Person { private String name = "Bob"; public String getName() { return name; } } public class Main { public static void main(String[] args) { Person p = new Person(); System.out.println(p.getName()); } }
Attempts:
2 left
π‘ Hint
Private members can be accessed inside the class and exposed via public methods.
β Incorrect
The private field 'name' is accessed through the public method getName(), so it prints 'Bob'.
β Predict Output
advanced2:00remaining
Effect of private data member shadowing
What is the output of this Java code?
Java
class Animal { private String type = "Animal"; public String getType() { return type; } } class Dog extends Animal { private String type = "Dog"; public String getType() { return type; } } public class Main { public static void main(String[] args) { Animal a = new Dog(); System.out.println(a.getType()); } }
Attempts:
2 left
π‘ Hint
Method overriding works even if private fields are shadowed.
β Incorrect
The variable 'a' is of type Animal but refers to a Dog object. The getType() method is overridden in Dog and returns Dog's private 'type'.
π§ Debug
advanced2:00remaining
Identify the error with private data member access
Which option correctly identifies the error in this code snippet?
Java
class Car { private int speed; public void setSpeed(int speed) { speed = speed; } public int getSpeed() { return speed; } } public class Main { public static void main(String[] args) { Car c = new Car(); c.setSpeed(50); System.out.println(c.getSpeed()); } }
Attempts:
2 left
π‘ Hint
Look at the assignment inside setSpeed method.
β Incorrect
Inside setSpeed, the parameter 'speed' shadows the field 'speed'. The assignment 'speed = speed;' assigns the parameter to itself, leaving the field unchanged.
π§ Conceptual
expert2:00remaining
Why use private data members in Java?
Which option best explains the main reason for declaring data members as private in Java?
Attempts:
2 left
π‘ Hint
Think about encapsulation and data protection.
β Incorrect
Private data members hide the internal state of an object and force access through methods, allowing validation and control.