1Z0-811 1Z0-811 Java Methods and Scope 3 — Questions and Answers
Question 1: What is method chaining in Java?
- Calling a method from within another method of a different class
- Calling multiple methods sequentially on the same object by returning `this` (Correct answer)
- Defining methods in a chain of inheritance
- Overloading a method more than three times
Correct answer: Calling multiple methods sequentially on the same object by returning `this`
Method chaining allows multiple method calls to be linked on the same object when each method returns `this` or another object.
Question 2: Which of the following method signatures would cause a compilation error due to ambiguity in overloading?
- void test(int a) and void test(double a)
- void test(int a) and void test(int a, int b)
- void test(int a) and int test(int a) (Correct answer)
- void test(int a) and void test(String a)
Correct answer: void test(int a) and int test(int a)
Two methods with the same name and parameter list but different return types are not valid overloads and cause a compilation error.
Question 3: What does it mean for a method to be `final`?
- It must be called last in a program
- It cannot be overridden in a subclass (Correct answer)
- It cannot accept any parameters
- It runs only once per application lifecycle
Correct answer: It cannot be overridden in a subclass
A `final` method cannot be overridden by subclasses, ensuring its behavior remains unchanged in the inheritance hierarchy.
Question 4: In Java, where can a local variable be declared?
- Only at the beginning of a method body
- Anywhere inside a block where it is needed (Correct answer)
- Only outside of all control flow structures
- Only as the first statement in a class
Correct answer: Anywhere inside a block where it is needed
Local variables in Java can be declared anywhere inside a block, but they must be initialized before use.
Question 5: Which statement about abstract methods is correct?
- Abstract methods must have a body
- Abstract methods can only be declared in interfaces
- Abstract methods have no body and must be implemented by concrete subclasses (Correct answer)
- Abstract methods can be declared static
Correct answer: Abstract methods have no body and must be implemented by concrete subclasses
An abstract method has no implementation body and requires any concrete (non-abstract) subclass to provide its implementation.
Question 6: What is the correct way to call a static method `calculate` from the same class `MathUtil`?
- new MathUtil().calculate()
- MathUtil.calculate() or just calculate() within the class (Correct answer)
- this.calculate()
- super.calculate()
Correct answer: MathUtil.calculate() or just calculate() within the class
Static methods are called on the class name (e.g., `MathUtil.calculate()`) or simply by method name within the same class without an object reference.
What is method chaining in Java?