Java Questions 21 - 30  «Prev  Next»

Java Questions 30

  1. If a method is private within a class, and is only visible from within the class, how can the private method be invoked?
    Answer:
    You can invoke a private method with reflection. Modifying the last bit of the posted code:
    method = object.getClass().getDeclaredMethod(methodName);
    method.setAccessible(true);
    Object r = method.invoke(object);
    

    There are a few elements that need to be observed when using this method.
    First, getDeclaredMethod will only find the method declared in the current Class, not inherited from supertypes.
    Traverse up the concrete class hierarchy if necessary.
    Second, a SecurityManager can prevent use of the setAccessible method. It may need to run as a PrivilegedAction (using AccessController or Subject).
  2. What is one way to call a private method?
    Answer:
    The only way to call a private method is from within the class in which it is declared?
  3. What type of method invocations are allowed by the compiler?
    Answer:
    Method invocations allowed by the compiler are based solely on the declared type of reference, regardless of the object type.
  4. Can a class implement two interfaces that have the same method name?
    Answer:
    The code below will only compile if the two interfaces contain methods that have the same return type.
    package com.oca.class_relationships;
    
    interface Fish { int getNumberOfScales(); }
    interface Piano { int getNumberOfScales(); }
    
    class Tuna implements Fish, Piano {
     public  int getNumberOfScales() { return 91; }
    }
    
  5. What is the dynamic difference between a reference type at compile time and an object at runt time?
    Answer:
    Even though the compiler only knows about the declared reference type, the JVM knows at runtime what the object really is.
  6. How are methods overridden by the JVM?
    Answer:
    The JVM looks at the real object at the other end of the reference, sees that it has overridden the method of the declared reference variable type, and invokes the method of the object's actual class.

  7. What methods are dynamically selected based on the actual object?
    Answer:
    Instance Methods: The only things that are dynamically selected based on the actual object (rather than the reference type) are instance methods.
  8. What is the key benefit of overriding?
    Answer:
    The key benefit of overriding is the ability to define behavior that is specific to a particular subclass type.
  9. How are abstract methods implemented?
    Answer:
    Abstract methods must be implemented by the concrete subclass.
  10. What portion of code does the compiler look at?
    Answer:
    The compiler looks only at the reference type, not the instance type.