Challenge - 5 Problems
Private Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of accessing private field within the same class
What is the output of this Java program?
Java
public class Test { private int number = 5; public void printNumber() { System.out.println(number); } public static void main(String[] args) { Test t = new Test(); t.printNumber(); } }
Attempts:
2 left
💡 Hint
Private fields can be accessed inside the same class.
✗ Incorrect
The private field 'number' is accessed inside the class method 'printNumber', so it prints 5.
❓ Predict Output
intermediateOutput when accessing private field from another class
What happens when you try to compile and run this code?
Java
public class A { private int secret = 10; } public class B { public static void main(String[] args) { A a = new A(); System.out.println(a.secret); } }
Attempts:
2 left
💡 Hint
Private fields are not accessible outside their own class.
✗ Incorrect
The field 'secret' is private in class A, so class B cannot access it directly, causing a compilation error.
🔧 Debug
advancedWhy does this code cause a compilation error?
Identify the reason for the compilation error in this code snippet.
Java
class Person { private String name; public Person(String name) { this.name = name; } } class Employee extends Person { public Employee(String name) { super(name); } public void printName() { System.out.println(name); } }
Attempts:
2 left
💡 Hint
Private fields are not inherited directly accessible in subclasses.
✗ Incorrect
The private field 'name' in Person is not accessible in subclass Employee, so accessing it in printName causes a compilation error.
📝 Syntax
advancedWhich option correctly declares a private method and calls it within the same class?
Select the code snippet that compiles and runs correctly, printing "Hello".
Attempts:
2 left
💡 Hint
Private methods can be called inside the same class instance methods.
✗ Incorrect
Option A correctly declares a private instance method and calls it from a public instance method. The main method creates an instance and calls call(), which prints "Hello".
🚀 Application
expertHow many private fields are accessible in this nested class?
Given the code below, how many private fields of Outer are accessible directly inside Inner?
Java
public class Outer { private int a = 1; private int b = 2; int c = 3; public class Inner { public int sum() { return a + b + c; } } }
Attempts:
2 left
💡 Hint
Inner classes can access all members of the outer class, including private ones.
✗ Incorrect
Inner class can access all fields of Outer, including private fields 'a' and 'b' (and package-private 'c'), so both private fields are accessible directly inside Inner.
