Comet opens sample.py on one side of the bench. "This was our very first class," she says proudly. "What would it look like in Java?"
Nova projects Sample.java right beside it. "How can I help?" she asks. "This version keeps only the label, the kind and the grams."
Wren reads both, line by line, with his pencil. "What do you notice? There is a word that looks a lot like self."
Comet points at private. "And this word hides the fields, like our underscore did for the rover."
Nova adds one more file, SampleDemo.java, and dims the output. "Predict first," she says. "Then I will show you what my run printed."
// Sample.java
// The same Sample class as sample.py, written in Java.
public class Sample {
private String label;
private String kind;
private int grams;
public Sample(String label, String kind, int grams) {
this.label = label;
this.kind = kind;
this.grams = grams;
}
public String getLabel() {
return label;
}
public int getGrams() {
return grams;
}
public boolean isHeavy() {
return grams >= 50;
}
public String describe() {
return label + " " + kind + " " + grams + " g";
}
} | sample.py (Python) | Sample.java (Java) |
|---|---|
| class Sample: | public class Sample { |
| def __init__(self, label, kind, grams, row=0, col=0): | public Sample(String label, String kind, int grams) { |
| self.label = label | this.label = label; |
| def is_heavy(self): | public boolean isHeavy() { |
| return self.grams >= 50 | return grams >= 50; |
// SampleDemo.java
public class SampleDemo {
public static void main(String[] args) {
Sample a = new Sample("S01", "basalt", 42);
Sample b = new Sample("S03", "clay", 65);
System.out.println(a.describe());
System.out.println(b.isHeavy());
System.out.println(a.getGrams() + b.getGrams());
}
} Here is what SampleDemo printed when Nova ran it:
S01 basalt 42 g true 107
# sample_demo.py
# The Python twin of SampleDemo.java.
from sample import Sample
a = Sample("S01", "basalt", 42)
b = Sample("S03", "clay", 65)
print(a.describe())
print(b.is_heavy())
print(a.grams + b.grams) S01 basalt 42 g at (0, 0) True 107
# sample_demo.py
# The Python twin of SampleDemo.java.
from sample import Sample
a = Sample("S01", "basalt", 42, 0, 2)
b = Sample("S03", "clay", 65)
print(a.describe())
print(b.is_heavy())
print(a.get_grams() + b.grams) S01 basalt 42 g at (0, 2)
True
Traceback (most recent call last):
File "sample_demo.py", line 9, in <module>
print(a.get_grams() + b.grams)
^^^^^^^^^^^
AttributeError: 'Sample' object has no attribute 'get_grams' You read a whole Java class and predicted its output, lead programmer. Tomorrow Nova shows the field grid in Java.