Challenge - 5 Problems
Default Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of default access modifier in same package
What is the output of this Java code when both classes are in the same package?
Java
class A { int number = 10; // default access } public class Test { public static void main(String[] args) { A a = new A(); System.out.println(a.number); } }
Attempts:
2 left
💡 Hint
Default access allows access within the same package.
✗ Incorrect
The variable 'number' has default access, so it is accessible within the same package. Since both classes are in the same package, the code prints 10.
❓ Predict Output
intermediateAccessing default member from different package
What happens when you try to access a default access member from a class in a different package?
Java
package pkg1; class B { int value = 5; // default access } package pkg2; import pkg1.B; public class Test { public static void main(String[] args) { B b = new B(); System.out.println(b.value); } }
Attempts:
2 left
💡 Hint
Default access members are not visible outside their package.
✗ Incorrect
The member 'value' has default access and is not visible outside its package. Trying to access it from another package causes a compilation error.
🔧 Debug
advancedWhy does this code fail to compile?
This code tries to access a default access method from another package. Identify the cause of the compilation error.
Java
package pkg1; class C { void show() { System.out.println("Hello"); } // default access } package pkg2; import pkg1.C; public class Test { public static void main(String[] args) { C c = new C(); c.show(); } }
Attempts:
2 left
💡 Hint
Check the access level of method show() and package visibility.
✗ Incorrect
The method show() has default access, so it is only accessible within the same package. Since Test is in a different package, the call c.show() causes a compilation error.
🧠 Conceptual
advancedDefault access modifier and subclassing
If a class with default access modifier is subclassed in the same package, can the subclass access the default members of the superclass?
Attempts:
2 left
💡 Hint
Think about package-level visibility and inheritance.
✗ Incorrect
Default access members are accessible anywhere within the same package, including subclasses. So subclasses in the same package can access default members.
❓ Predict Output
expertNumber of accessible members with default access
Given this class with default access members, how many members are accessible from another class in the same package?
Java
class D { int a = 1; // default private int b = 2; protected int c = 3; public int d = 4; }
Attempts:
2 left
💡 Hint
Remember which access modifiers allow access within the same package.
✗ Incorrect
From the same package, default, protected, and public members are accessible. Private members are not accessible. So members a, c, and d are accessible, total 3.
