Java OCA OCP Practice Question 2364

Question

What is the output? Choose the best answer.

interface Printable {
    String course = "OCP";
    int duration = 2;
 }
class Main implements Printable {
    String course = "OCA";
    public static void main(String args[]) {
        Main m = new Main();
        System.out.print(m.course);             // n1
        System.out.print(Main.duration);     // n2
    }/*w w w.j  a va  2  s .  co  m*/
 }
  • a Compilation fails at line n1.
  • b Compilation fails at line n2.
  • c Compilations fails at both lines n1 and n2.
  • d Code prints "OCA2".
  • e Code prints "OCP2".
  • f Code throws a runtime exception.


d

Note

Class Main defines an instance variable course.

Interface Printable also defines a variable with the same name-course (which is implicitly static).

Class Main implements Printable.

Using Main's instanceName.

course will refer to its instance variable.

Using Printable.course will refer to the variable course from Printable.

Using Main.course will result in a compilation error.

Code on line n1 compiles successfully and prints OCA.

Because the variables defined in an interface are implicitly static and final, the variable duration can be accessed as Main.duration.

Code on line n2 compiles successfully and prints 2.

However, a class can't define static and instance variables with the same name.

The following class won't compile:.

class Main {
    String course;
    static String course;
}



PreviousNext

Related