Java OCA OCP Practice Question 2642

Question

Consider the following program:

class SuperClass {
        SuperClass() {// www.  j a va2  s. c o m
                foo();
        }
        public void foo(){
                System.out.println("In SuperClass.foo()");
        }
}
class Main extends SuperClass {
        public Main() {
                member = "HI";
        }
        public void foo() {
                System.out.println("In Derived.foo(): " + member.toLowerCase());
        }
        private String member;
        public static void main(String[] args) {
                SuperClass reference = new Main();
                reference.foo();
        }
}

This program prints the following:

a)In SuperClass.foo()

b)In Derived.foo(): hi

c)In SuperClass.foo()
  In Derived.foo(): hi

d)This program throws a NullPointerException.


d)

Note

In this program, the SuperClass constructor calls the method foo() that is overridden in the derived class.

Thus, in this program, since the Main object is created, the call to the SuperClass constructor will result in calling the method Main.foo().

When the derived class object is created, first the base class constructor is called, followed by the call to the derived class constructor.

Note that the member variable is initialized only in the derived class constructor.

Thus, when the base class constructor executes, the derived class constructor has not initialized the member variable to "HI" yet.

So this program results in a NullReferenceException.




PreviousNext

Related