Question discussion

What will happen when the code is executed?

359225Medium DSSSB TGT Computer Science 0 replies 0 views
0
What will happen when the code is executed?
class Parent {
    protected void protectedMethod() {
        System.out.println("Protected method in Parent");
    }
}
class Child extends Parent {
    public void childMethod() {
        protectedMethod();
    }
}
public class Test {
    public static void main(String[] args) {
        Child child = new Child();
        child.childMethod();
    }
}
  • AThe code will compile and print 'Protected method in Parent'.
  • BCompilation Error: The protectedMethod is not visible in the Child class.
  • CCompilation Error: childMethod is not visible due to access restrictions.
  • DRuntime Error: Cannot access protectedMethod from the Child class.
Correct answer: A

Explanation

A protected method is accessible in a subclass, so childMethod() can call protectedMethod(). The program prints "Protected method in Parent".

Discussion 0

Nobody has replied yet. Start the discussion!