3 ms·
This is how most object-oriented languages work, people just don't realize it. Here's some Java code: class Base { private int field;
by munificent 8y ago
This is how most object-oriented languages work, people just don't realize it. Here's some Java code:
class Base {
private int field;
Base() {
this.field = 1;
}
void baseMethod() {
System.out.println("Base.field = " + field);
}
}
class Derived extends Base {
private int field;
Derived() {
this.field = 2;
}
void derivedMethod() {
System.out.println("Derived.field = " + field);
}
}
public static void main(String[ ] args) {
Derived d = new Derived();
d.baseMethod();
d.derivedMethod();
}
It prints:
Base.field = 1
Derived.field = 2
- throwaway427 8y agoThis is not how Ruby and Python works, I believe. I guess it's debatable which paradigm JavaScript is more similar to.
- munificent 8y agoPython name-mangles properties that start with "__" to emulate privacy. Run: class Base: def __init__(self): self.__field = 1 def baseMethod(self): print("baseMethod " + str(self.__field)) class Derived(Base): def __init__(self): super().__init__() self.__field = 2 def derivedMethod(self): print("barMethod " + str(self.__field)) d = Derived() d.baseMethod() d.derivedMethod() And it prints: baseMethod 1 barMethod 2 Ruby doesn't really have fields that are private to subclasses, but Ruby also embraces monkey-patching, so that's not entirely surprising.