Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

java - Confusing "override a private method"

I have two question on this code

public class Override {
    private void f() {
        System.out.println("private f()");
    }
    public static void main(String[] args) {
        Override po = new Derived();
        po.f();
    }
}

class Derived extends Override {
    public void f() {
        System.out.println("public f()");
    }
} 

/*
* Output: private f()
*/// :~

1) How is function f is visible on the reference of Override po;

2) Why is output "private f()"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. The main method is inside class Override, so ofcourse it can see the private members of class Override.

  2. You are not overriding method f in class Derived, there is no polymorphism. The type of the variable po is Override, so it will take method f from class Override.

Note that method f in class Override is not visible at all in class Derived. The method f in class Derived is a different method, that doesn't have anything to do with the method f in the superclass.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...