Java Questions 21 - 30  «Prev  Next»

Java Access Modifiers for Variables and Methods

  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:
    In Java, a `private` method is only accessible within the class in which it is declared. This means it cannot be accessed directly from outside the class, not even by subclasses. However, the method can be invoked internally by other methods within the same class.
    How to Invoke a Private Method:
    A `private` method can be invoked directly by any other method inside the same class. Here is how it works:
    1. Direct Invocation Inside the Class:
      • You can call a `private` method from any non-static or static method within the same class.
      • The method call follows the same syntax as any other method, but it must be within the same class.

    Example:
    class MyClass {
       // Private method
       private void displayMessage() {
           System.out.println("Hello from a private method!");
       }
       // Public method that calls the private method
       public void callPrivateMethod() {
           displayMessage();  // Private method invoked here
       }
    }
    
    public class Main {
       public static void main(String[] args) {
           MyClass obj = new MyClass();
           obj.callPrivateMethod();  // indirectly calls the private method
       }
    }
    

    Explanation:
    • The `displayMessage()` method is `private`, so it cannot be accessed directly from outside `MyClass`.
    • However, within `MyClass`, the `callPrivateMethod()` public method invokes `displayMessage()`.
    • When you create an object of `MyClass` and call `callPrivateMethod()`, it indirectly triggers the execution of the `private` method `displayMessage()`.

    Summary: A `private` method can be invoked directly by other methods within the same class. To expose the functionality of a `private` method indirectly, you can create a public or protected method that calls the `private` method internally.
    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 in Java SE 22?

    Answer:
    In Java SE 22, the key benefit of method overriding remains the same as in previous versions, with some optimizations in performance and maintainability. The most significant benefits include:
    1. Runtime Polymorphism
      • Overriding enables dynamic method dispatch, allowing Java to determine the method to call at runtime, based on the object's actual type rather than the reference type.
      • This is fundamental to achieving flexible and extensible software design.
    2. Improved Code Maintainability
      • By overriding methods from a superclass or an interface, you can modify behavior without changing the original class.
      • This is useful when working with APIs, libraries, or frameworks that define abstract or default methods.
    3. Enhanced Readability and Reusability
      • Instead of duplicating code, you can reuse and extend existing behavior.
      • Child classes only need to override specific methods, keeping the code modular and readable.
    4. Integration with Modern Java Features (Records, Sealed Classes)
      • Java SE 22 continues improvements in sealed classes and records, where overriding plays a critical role.
      • Sealed classes (sealed keyword) allow controlled overriding, ensuring only permitted subclasses extend functionality.
      • Records (record keyword) prevent unnecessary overriding by enforcing immutability but allow selective customization.
    5. Performance Optimizations in JVM
      • The JIT compiler (Just-In-Time compilation) and other JVM optimizations ensure overridden methods are efficiently executed.
      • Escape analysis and inlining reduce the performance overhead when invoking overridden methods.
    6. Default Methods in Interfaces
      • Overriding plays a key role in interface evolution, as Java SE 22 continues to support default methods (default keyword).
      • This allows interfaces to add new methods without breaking existing implementations, while still permitting overriding for customization.

    Example in Java SE 22: Sealed Classes and Overriding
    sealed class Animal permits Dog, Cat {
        void sound() {
            System.out.println("Animal makes a sound");
        }
    }
    
    final class Dog extends Animal {
        @Override
        void sound() {
            System.out.println("Dog barks");
        }
    }
    
    final class Cat extends Animal {
        @Override
        void sound() {
            System.out.println("Cat meows");
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            Animal myDog = new Dog();
            myDog.sound();  // Output: Dog barks
    
            Animal myCat = new Cat();
            myCat.sound();  // Output: Cat meows
        }
    }
    


    Here, overriding ensures that the correct subclass method (`Dog` or `Cat`) is executed at runtime.
    Conclusion: The primary benefit of overriding in Java SE 22 is to enable polymorphism, maintainability, and extensibility, with optimizations through sealed classes, records, and JVM performance improvements.



  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.

SEMrush Software