这是第一堂课
package test;
public class Project {
public void doSomething (String stuff) {
writeStuff();
whichProject(stuff);
}
public void writeStuff(){
System.out.println("This is stuff");
}
public void whichProject(String stuff){
System.out.println("This is a random project " + stuff);
}
}
这是派生类
package test;
public class Project1 extends Project{
public void whichProject(String stuff){
System.out.println("Coding project number one: " + stuff);
}
public static void main(String[] args) {
Project project = new Project1();
project.doSomething("stuff");
}
}
运行 Project1 时,输出结果为:
This is stuff
Coding project number one: stuff
为什么它whichProject()
在 Project1 中调用而不是在 Project 中调用?毕竟,不是doSomething()
Project中的方法吗?或者当基类中有一个方法位于基类中的另一个方法中时,即使我们在另一个方法中,变量所引用的对象仍然决定将调用哪个方法调用?
现在,如果我们改变 to 的修饰符,whichProject()
那么private
现在的类是
package test;
public class Project {
public void doSomething (String stuff) {
writeStuff();
whichProject(stuff);
}
public void writeStuff(){
System.out.println("This is stuff");
}
private void whichProject(String stuff){
System.out.println("This is a random project " + stuff);
}
}
输出变为:
This is stuff
This is a random project stuff
所以现在whichProject()
正在调用 Project 中的方法,而不是 Project1,即使变量引用了 Project1 的对象。在这种情况下,我根本不明白发生了什么。对这两种情况(whichProject()
带有public
修饰符和whichProject()
修饰符private
)的解释将不胜感激。