Menu
CoddyTech

Composition and Delegation

Lesson 38 of 48 in Coddy's Java for C# Developers course.

C# and Java can express constructor-injected collaborators through explicit interfaces. Unlike structural typing, merely defining a matching method does not make an unrelated class implement the demonstrated interface. Delegate calls to the supplied dependency so alternate implementations remain useful. Constructor injection stores a collaborator selected by the caller. Invoke its behavior instead of reconstructing a default or duplicating a calculation. A declared interface can admit implementations with different policies while keeping the consumer stable.

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {
interface IRate{int Cost(int n);}class SpecialRate:IRate{public int Cost(int n){return n+17;}}class Bill{private readonly IRate rate;public Bill(IRate rate){this.rate=rate;}public int Total(int n){return rate.Cost(n);}}
static void Main() {
Console.WriteLine(new Bill(new SpecialRate()).Total(5));
}
}

Java

import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Example {
interface Rate {int cost(int n);}static class Bill {private final Rate rate;Bill(Rate rate){this.rate=rate;}int total(int n){return rate.cost(n);}}
public static void main(String[] args) {
Bill b=new Bill(n->n+17);System.out.println(b.total(5));
}
}

Porting trap

Preserve the injected object instead of allocating a replacement inside the consumer.

Apply the comparison in the editable task files. These standalone examples use their own entry points; the exercise API is Exercise.solve, called by the visible locked Main.java.

challenge icon

Challenge

Easy

Input is unit rate then units, both nonnegative. Implement Rate(int) with cost(int), and UsageBill(Rate) with total(int) delegating to its supplied collaborator. Return total.

Return the exact result text without a final newline from Exercise.solve(List<String> input). The visible locked Main.java reads all input lines and prints the returned text with one final newline. Do not print inside editable methods. All integers and arithmetic results fit Java int unless stated otherwise.

Editable files: Rate.java, UsageBill.java, Exercise.java, Text.java. Text.java supplies reusable parsing and formatting helpers. All files are in the unnamed package and compile together. Main.java is the only entry point and cannot be edited.

The visible locked driver also calls the required class APIs on independent fresh objects before running the input case. Implement those APIs; hard-coding the final output alone is insufficient.

Try it yourself

import java.io.*;
import java.util.*;
public class Main {
    private static void check(boolean condition) {
        if (!condition) throw new AssertionError("Required public API behavior failed");
    }
    public static void main(String[] args) throws Exception {
        List<String> input = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = reader.readLine()) != null) input.add(line);
        check(new Rate(6).cost(3)==18);Rate special=new Rate(1){public int cost(int n){return n+17;}};check(new UsageBill(special).total(5)==22);
        System.out.println(Exercise.solve(input));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Java for C# Developers

Practice on your own: Online Java compiler