007-002-012

Object Creation: Method Chaining

Hard

Problem Description

Object Creation: Method Chaining

In this problem, you will implement method chaining in a Builder class with setName() and setValue() methods that return this, along with a build() method.

Learning Objective: Implement method chaining using methods that return this

Overview

Implement a fluent API using method chaining.

Specifications

  • Create a Builder class
  • Define String name and int value fields
  • setName(String name) method: set the name field and return this
  • setValue(int value) method: set the value field and return this
  • build() method: return a string in the format name + " - " + value

Usage Example

Builder b = new Builder();
String result = b.setName("Test").setValue(42).build();
System.out.println(result); // Test - 42

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up