0
0
Javaprogramming~15 mins

Default access modifier in Java - Practice Problems & Coding Challenges

Choose your learning style8 modes available
trophyChallenge - 5 Problems
🎖️
Default Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 code output
intermediate
2:00remaining
Output 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);
    }
}
A10
BCompilation error: number has private access in A
CCompilation error: number is not public in A
DRuntime error
Attempts:
2 left
💻 code output
intermediate
2:00remaining
Accessing 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);
    }
}
A5
BCompilation error: value is not public in B
CCompilation error: B() has private access in B
DRuntime error: IllegalAccessException
Attempts:
2 left
🔧 debug
advanced
2:00remaining
Why 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();
    }
}
AClass C is abstract and cannot be instantiated
BClass C is public but method show() is private
CMethod show() has default access and is not visible outside pkg1
DMethod show() is static and should be called on class
Attempts:
2 left
🧠 conceptual
advanced
2:00remaining
Default 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?
ANo, default members are only accessible within the same class
BNo, default members are not accessible to subclasses even in the same package
CYes, but only if the subclass is in a different package
DYes, default members are accessible to subclasses in the same package
Attempts:
2 left
💻 code output
expert
2:00remaining
Number 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;
}
A3
B4
C2
D1
Attempts:
2 left