Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 70
Question ID: UKOCP79426
Consider below code of Test.java file:
- package com.udayankhattry.ocp;
- class Shape {
- int side = 0; //Line n1
- int getSide() { //Line n2
- return side;
- }
- }
- class Square extends Shape {
- private int side = 4; //Line n3
- protected int getSide() { //Line n4
- return side;
- }
- }
- public class Test {
- public static void main(String[] args) {
- Shape s = new Square();
- System.out.println(s.side + ":" + s.getSide());
- }
- }
What will be the result of compiling and executing above code?
- A Compilation error at Line n3
- B Compilation error at Line n4
- C 0:0
- D 0:4
- E 4:4
- F 4:0
Reveal correct answer
Correct answer: D
Explanation
UKOCP79426:
Subclass overrides the methods of superclass but it hides the variables of superclass.
Line n3 hides the variable created at Line n1 and Line n4 overrides the getSide() method of Line n2. There is no compilation error for Square class as it correctly overrides getSide() method. You can use any access modifier at Line n3 as well, there are no rules for variable hiding.
's' is of Shape type, hence s.side equals to 0 and s.getSide() invokes overriding method of Square class and it returns 4. Hence output is: 0:4.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
