Java私有变量继承疑问:子类为何能调用父类含私有变量的方法?
Why Does This Java Code Work, and Is It Similar to JavaScript Closures?
First, let’s look at your code for reference:
class Rodent { private String hello = "hello" ; public void printHello() { System.out.println(hello); } } public class Mouse extends Rodent { public static void main(String[] args) { Mouse mouse = new Mouse(); mouse.printHello(); } }
Great question—this is a common point of confusion when learning Java inheritance. Let’s break down why this works first, then compare it to JavaScript closures.
Why the Code Runs Successfully
Here’s the key logic at play:
- When you create a
Mouseinstance, it includes all members of its parent classRodent—even the privatehellovariable. Subclasses can’t directly access parent private members (you couldn’t writethis.helloinsideMouse), but those members still exist as part of the subclass instance’s internal structure. - The
printHello()method is defined inRodent, and as a member of that class, it has full access to all private members ofRodent—regardless of which instance (parent or child) calls it. Whenmouse.printHello()runs, the method is executingRodent’s code, which can freely access thehellovariable that’s part of the instance’s parent-class segment.
Put simply: Java’s access control is based on the class where the method is defined, not the class of the object calling the method.
Is This Similar to JavaScript Closures?
There’s a superficial overlap (a method/function accessing a variable that feels "off-limits" to the caller), but the underlying mechanisms are completely different:
- JavaScript closures depend on lexical scoping: a function retains access to variables from the scope where it was created, even when executed outside that scope. For example, an inner function can access an outer function’s variables long after the outer function has finished running.
- Java’s method access is purely about class-based permission rules. The
printHello()method doesn’t "close over" thehellovariable—it’s allowed to access it simply because it belongs to the same class that defineshello. There’s no lexical scope retention here; it’s a core part of Java’s object-oriented design.
内容的提问来源于stack exchange,提问作者Number945
相关产品推荐
相关产品推荐

