AddMemberAtRuntime
One can add, remove, or rename members (fields, methods) of a class at runtime.
Set of class members can change at runtime
Set of class members stays fixed at runtime
CorrectionHere is what's right.
The set of members of a class is a defining characteristic of the class type. In Java, the class (i.e., type) of an object cannot change at runtime: neither can one change which class an object has, nor can one change the definition of that class (e.g., which fields or methods the class has).
class Point {
int x;
}
Point p = new Point();
p.x = 1; // OK (can change value of field x)
p.y = 10; // ERROR: cannot add field y
delete(p.x); // ERROR: cannot remove field from an object
OriginWhere could this misconception come from?
Students might have this misconception about Java classes if they are already familiar with more dynamic languages like JavaScript or Python, where “fields” can be added to objects at runtime.
SymptomsHow do you know your students might have this misconception?
A variant of this misconception (about being able to not add but modify methods)
showed up repeatedly
when discussing whether method g
in the following class was pure:
public class C {
private static int f(int x) {
return -x;
}
public int g(int value) {
return value + f(value);
}
}
Students argued that g
was not pure because f
might change.
They often did not specify exactly how they imagined how f
might be changed at runtime,
but some mentioned that f
might be assigned a lambda.