โ† All 1Z0-811 Flashcard Decks

Java Class Design Flashcards

5 cards from real 1Z0-811 practice questions. Tap to flip, then mark Knew It or Still Learning โ€” missed cards come back until you master them.

Read the first 5 Java Class Design flashcards as text
  1. What is the result of attempting to compile and run the following code? class A { public void method() { System.out.println("A"); , } } class B extends A { public void method() { System.out.println("B"); } } public class Test { public static void main(String[] args) { A obj = new B(); obj.method(); } }

    Answer: "B"

    This code demonstrates polymorphism and method overriding. Although `obj` is declared as type `A`, it is instantiated as an object of type `B`. When `obj.method()` is called, Java uses dynamic method dispatch, meaning the actual method executed is determined by the runtime type of the object, which is `B`. Therefore, the `method()` implementation from class `B` is invoked, printing 'B'.

  2. Which access modifier allows access to a class member only within the same package and subclasses?

    Answer: protected

    The `protected` access modifier allows a class member to be accessed from within the same package and by any subclass, regardless of whether the subclass is in the same package or a different one. This provides a balance between strict encapsulation (`private`) and broad accessibility (`public`), enabling controlled inheritance.

  3. How can you create a class that cannot be subclassed?

    Answer: By using the final keyword

    To prevent a class from being subclassed, you must use the `final` keyword in its declaration. A `final` class cannot be extended, meaning no other class can inherit from it. This is often used for security reasons or to ensure immutability and prevent unintended modifications to class behavior.

  4. What is method overloading in Java?

    Answer: Defining multiple methods with the same name but different parameter lists

    Method overloading in Java occurs when a class has multiple methods with the same name but different parameter lists. The compiler distinguishes between these methods based on the number, type, or order of their parameters. The return type alone is not sufficient to differentiate overloaded methods.

  5. What is the purpose of the "super" keyword in Java?

    Answer: To call the superclass constructor

    The `super` keyword in Java is primarily used to refer to the immediate superclass. Its most common use is `super()` to explicitly call a constructor of the superclass from within a subclass's constructor. It can also be used to access superclass members (methods or fields) that have been overridden or hidden in the subclass.