Java Questions 31 - 40  «Prev  Next»

Upcasting | Downcasting (Java Questions)

  1. What is downcasting?

    Answer:
    This is when we are casting down the inheritance tree to a more specific class.

  2. What can the compiler verify with respect to inheritance?

    Answer:
    All the compiler can do is verify that the 2 types are in the same inheritance tree.

  3. How is the syntax for upcasting different from downcasting?

    Answer:
    Unlike downcasting, upcasting (casting up the inheritance tree to a more general type) works implicitly (that means you do not have to type in the cast).

  4. What must you observe between a subclass and superclass when implementing an interface?

    Answer:
    You must know what the superclasses of the implementing class have declared. If any superclass in its inheritance tree has already provided concrete (i.e. non-abstract) method implementations, then, regardless of whether the superclass declares that it implements the interface, the subclass is not required to re-implement (override) those methods.

  5. How can the following lines of code be rewritten in a more compact manner?
    Animal a = new Dog();
    Dog d = (Dog) a;
    d.doDogStuff();
    


    Answer:
    The above can be rewritten as
    Animal a = new Dog();
    ((Dog)a).doDogStuff();
    

  6. What does the Java compiler do with any class that claims to implement an interface?

    Answer:
    Java runs a compiler check on any class that claims to implement an interface.

  7. When a class implements the method of an interface, what must be respected by the method in the class ?

    Answer:
    The method in the class cannot throw an exception unless the Interface itself throws the exception.
    Declare no checked exceptions on implementation methods other than those declared by the interface method, or subclasses of those declared by the interface method.

  8. Can an abstract class implement an interface?

    Answer:
    Yes, A class that implements an interface can be abstract.

  9. Can a class implement more than one interface?

    Answer:
    Yes, a class can implement more than one interface.
    public class AL extends Frame implements WindowListener, ActionListener
    

  10. Can an interface implement another interface?

    Answer:
    No. An interface can extend another interface,but canot implement anything.
    public interface Bounceable extends Moveable{}