Menu
CoddyTech

方法与 this

Coddy 面向 C++ 开发者的 Java 课程的第 34 课,共 48 课。

Java 实例方法使用 this 访问接收者,与 C++ 方法一样。Java 没有带 const 限定的实例方法重载。请分别验证每个导出的类方法,确保包装器无法用最终输出的计算取代所有必需的对象行为。

C++

#include <iostream>
#include <optional>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <functional>
#include <stdexcept>
struct Counter { int n=0; int next() { return ++n; } };
int main() {
  std::cout << std::boolalpha;
  Counter c; std::cout << c.next() << " " << c.next() << "\n";
}

Java

import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Example {
static class Counter {int value;void add(int n){value+=n;}}
public static void main(String[] args) {
Counter a=new Counter(),b=new Counter();IntConsumer f=a::add;f.accept(3);System.out.println(a.value+" "+b.value);
}
}

这些示例分别展示语言行为,可能使用不同的值。请分别跟踪执行过程,不要假定它们的预期输出相同。Java 任务通过可编辑的类,将相同概念应用于新的输入。

challenge icon

挑战

简单

输入依次为初始值和两次加法。实现 Counter(int start)、私有的 value、返回新值的 add(int),以及 getValue()。依次返回两次加法的结果,然后返回最后一次 getter 的结果。

从 Exercise.solve(List<String> input) 返回不带末尾换行符的确切结果文本。可见的锁定文件 Main.java 会读取所有输入行,并在打印返回文本时添加一个末尾换行符。不要在可编辑的方法中打印内容。除非另有说明,所有整数和算术结果都能放入 Java int。

可编辑文件:Counter.java、Exercise.java、Text.java。Text.java 提供可复用的解析和格式化辅助方法。所有文件都在未命名包中,并会一起编译。Main.java 是唯一入口点,不能编辑。

可见的锁定驱动程序还会在运行输入用例之前,使用独立的新对象调用所需的类 API。请实现这些 API;仅对最终输出进行硬编码是不够的。

亲手试试

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);
        Counter ca=new Counter(8),cb=new Counter(-2);check(ca.add(3)==11&&ca.add(-1)==10&&ca.getValue()==10&&cb.getValue()==-2);
        System.out.println(Exercise.solve(input));
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C++ 开发者的 Java中的所有课

自己练习: Java 在线编译器