Java OCA OCP Practice Question 2703

Question

Consider the following class definition:

abstract class Base {
        public abstract Number getValue();
}

Which of the following two options are correct concrete classes extending Base class?

a)  class Deri extends Base {
          protected Number getValue() {
                  return new Integer(10);
          }/*from  w  w  w .j a  v  a2  s  .  c  o m*/
    }

b)  class Deri extends Base {
          public Integer getValue() {
                  return new Integer(10);
          }
    }

c)  class Deri extends Base {
          public Float getValue(float flt) {
                  return new Float(flt);
          }
    }

d)  class Deri extends Base {
          public java.util.concurrent.atomic.AtomicInteger getValue() {
                  return new java.util.concurrent.atomic.AtomicInteger(10);
          }
    }


b)      

d)

Note

Option a) attempts to assign weaker access privilege by declaring the method protected when the base method is public, and thus is incorrect.

Option b) makes use of a co-variant return type (note that Integer extends Number), and defines the overriding method correctly.

In option c) the method Float getValue(float flt) does not override the getValue() method in Base since the signature does not match, so it is incorrect.

Option d) makes use of co-variant return type (note that AtomicInteger extends Number), and defines the overriding method correctly.




PreviousNext

Related