Java Questions 29
Java Questions 21 - 30  «Prev  Next»

References, Interfaces, and Resource Bundles in Java SE 25

Review object references, single class inheritance, multiple interfaces, encapsulation, and localized resources in Java SE 25.

  1. Is it accurate to say that every Java object is polymorphic?

    Answer: That statement is too imprecise to be a useful rule. Every object, including an array, can be referenced through Object, but polymorphism is better explained through how a program uses types and operations. An Object instance itself does not have an additional subclass identity.

    For subtype polymorphism, code uses a common type while different concrete implementations supply behavior through overridden instance methods. For example, a method accepting a List can work with an ArrayList or a LinkedList. The variable has a declared type; the object has a runtime class. These are related but distinct concepts.

  2. Must an object be accessed through a named reference variable?

    Answer: No. Operations on objects use reference values, but the reference can be the result of an expression rather than a named variable. For example, new StringBuilder().append("Java").toString() calls methods using references produced by object creation and method calls.

    A string literal, a factory method result, an array access, or this can also supply a reference. Assigning a reference to a variable is useful when the program needs to reuse it or make the code clearer, but it is not required for every method invocation.

  3. What is the difference between an object and a reference?

    Answer: An object is a class instance or an array created at runtime. A reference value identifies an object, or is null and identifies no object. A reference variable stores a reference value; it does not contain a copy of the whole object.

    For example, after StringBuilder first = new StringBuilder("A"); StringBuilder second = first;, both variables refer to the same builder. Calling second.append("B") changes the object also seen through first. Assigning second = null changes only that variable. Java does not expose reference values as addresses that application code can manipulate with pointer arithmetic.



  4. Can a reference variable refer to an object of a different class?

    Answer: Yes, when the object's type is compatible with the variable's declared type. A superclass variable can refer to a subclass object, and an interface variable can refer to an object whose class implements that interface. The object's runtime class is unchanged by the assignment.

    For instance, List<String> names = new ArrayList<>(); uses an interface reference for an ArrayList object. Type arguments still matter: List<Integer> is not a subtype of List<Number>. Wildcards can express selected relationships, such as List<? extends Number>, with corresponding restrictions on operations.

  5. Which types can reference variables have?

    Answer: Reference types include class types, interface types, type variables, and array types. Enum and record types are class types. Examples include String, Runnable, a generic type parameter T, and int[]. An array of primitives is still an object and its variable has a reference type.

    The null type cannot be written as the declared type of a variable. Also, var is not a dynamic reference type: in an eligible local variable declaration it asks the compiler to infer a static type from the initializer. The inferred type can be primitive or reference, and the usual assignment rules then apply.

  6. Does Java support multiple class inheritance?

    Answer: A class has at most one direct superclass. Every class except Object has one; Object has none. A declaration cannot extend two classes. An ordinary class can, however, implement multiple interfaces.

    This distinction avoids treating inheritance of class state and constructors as equivalent to implementing several contracts. Interfaces can extend multiple interfaces, and they can provide default methods, subject to conflict-resolution rules. Arrays have special language-defined supertypes rather than an ordinary class declaration with an extends or implements clause.


  7. Can a class have several ancestors despite having only one direct superclass?

    Answer: Yes. If C extends B and B extends A, C has B as its direct superclass and A as an indirect superclass. Object is also in the ancestry unless A is Object itself. This is multilevel inheritance, not multiple direct class inheritance.

    A C reference can be assigned to an A or B variable through a widening reference conversion. Accessible methods can be inherited through the chain, while overriding, hiding, access control, and constructor rules determine the details. Constructors themselves are never inherited down that chain.

  8. How can a Java class combine capabilities from several types?

    Answer: It can implement multiple interfaces and use composition to delegate work to other objects. For example, a class could implement Runnable and AutoCloseable while holding a separate object that performs storage operations.

    Implementing multiple interfaces does not give the class multiple class superclasses. If unrelated interfaces supply conflicting default implementations of the same method, the class generally needs an explicit override to resolve the conflict. Compatible abstract declarations may be satisfied by one implementation. Composition is useful when the desired relationship is collaboration rather than subtyping.

  9. How does encapsulation separate an object's interface from its implementation?

    Answer: Encapsulation exposes supported operations while keeping implementation details behind controlled boundaries. Callers should depend on documented behavior, not on how fields are arranged or which helper objects are used internally.

    Private fields are a common tool, but adding a getter and setter for every field can still expose too much. Methods such as reserve(quantity) can enforce a meaningful invariant more effectively than unrestricted state assignment. Returning a mutable internal collection can also break encapsulation; choose an appropriate snapshot, unmodifiable view, or controlled operation according to the contract.

  10. What is ResourceBundle used for?

    Answer: ResourceBundle loads locale-specific resources, commonly translated messages, by a shared base name and a Locale. Resources can be supplied in properties files or ResourceBundle subclasses such as ListResourceBundle. This separates localized text from application logic.

    Place these two UTF-8 properties files at the root of the example's classpath. Messages.properties supplies the base bundle:

    greeting=Hello
    

    Messages_fr.properties supplies the French translation:

    greeting=Bonjour
    
    import java.util.Locale;
    import java.util.ResourceBundle;
    
    public class BundleMessages {
        public static void main(String[] args) {
            ResourceBundle french = ResourceBundle.getBundle("Messages", Locale.FRENCH);
            ResourceBundle base = ResourceBundle.getBundle("Messages", Locale.ROOT);
            System.out.println(french.getString("greeting"));
            System.out.println(base.getString("greeting"));
        }
    }

    The output is Bonjour followed by Hello. Bundle lookup uses candidate locales and fallback rules; a missing key can be looked up in a parent bundle. If no suitable bundle or key is available, the lookup throws MissingResourceException. Use stable keys and test translations and fallback behavior rather than assuming every locale has a complete standalone file.

References: JLS: types and values, JLS: classes, JLS: interfaces, and ResourceBundle API.