You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Mouse instance, it includes all members of its parent class Rodent—even the private hello variable. Subclasses can’t directly access parent private members (you couldn’t write this.hello inside Mouse), but those members still exist as part of the subclass instance’s internal structure.
  • The printHello() method is defined in Rodent, and as a member of that class, it has full access to all private members of Rodent—regardless of which instance (parent or child) calls it. When mouse.printHello() runs, the method is executing Rodent’s code, which can freely access the hello variable 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" the hello variable—it’s allowed to access it simply because it belongs to the same class that defines hello. There’s no lexical scope retention here; it’s a core part of Java’s object-oriented design.

内容的提问来源于stack exchange,提问作者Number945

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:25:45