构造函数与状态
Coddy 面向 Lua 开发者的 Java 课程的第 33 课,共 48 课。
Lua 构造函数辅助函数是普通函数,会返回表,也可能会赋值元表。Java 构造函数使用类名,且没有返回类型。它们会在创建新对象时设置状态,声明任何构造函数都会移除隐式的无参数构造函数。需要时,应为每个实例单独分配可变集合;如果构造函数参数与属性同名,请使用 this.field。
Lua
local function new_score(points) return {points=points} end; local score=new_score(3); print(score.points)
Java
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Example {
static class Score {int points;Score(int points){this.points=points;}}
public static void main(String[] args) {
Score a=new Score(3);System.out.println(a.points);
}
}移植时的陷阱
Java 构造函数没有返回类型;以类名声明的 void 函数是普通方法。
使用下面可编辑的任务文件来应用这个区别。上面的示例是独立演示;此任务使用 Exercise.solve 和可见的锁定文件 Main.java 处理输入和输出。
挑战
简单输入分三行,分别是名称、初始分数和增量。实现 Scoreboard(String name,int points),用于存储公开的 name 和 points;add(int delta) 只修改该实例。返回名称、更新后的分数,以及另一个初始分数为 0 的记分板的分数。
让 Exercise.solve(List<String> input) 返回不带末尾换行符的确切结果文本。可见的锁定文件 Main.java 会读取所有输入行,并在打印返回文本时添加一个末尾换行符。不要在可编辑的方法中打印内容。除非另有说明,所有整数和算术结果都在 Java int 的范围内。
可编辑文件:Scoreboard.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);
Scoreboard sa=new Scoreboard("probe",4),sb=new Scoreboard("other",0);sa.add(-1);check(sa.name.equals("probe")&&sa.points==3&&sb.points==0);
System.out.println(Exercise.solve(input));
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Lua 开发者的 Java中的所有课
自己练习: Java 在线编译器