Java OCA OCP Practice Question 2354

Question

Select the correct options for the classes Shape and Main:

abstract class Shape{
    static {/*from w  ww . j  a v a 2 s . c  om*/
        ctr = (int)Math.random();              // line1
    }
    static final int ctr;                      // line2
}
class Main extends Shape{
    public static void main(String args[]) {
       System.out.println(Main.ctr);          // line3
    }
}
  • a Code at only (#1) fails compilation.
  • b Code at either (#1) or (#2) fails compilation.
  • c Code at (#3) fails compilation.
  • d Code compiles and executes successfully.


d

Note

No compilation or runtime issues exist with this code.

A static initializer block can access and initialize a static variable; it can be placed before the static variable declaration.

A static variable defined in a base class is accessible to its derived class.

Even though class Main doesn't define the static variable ctr, it can access the static variable ctr defined in its base class Shape.




PreviousNext

Related