This is the first class
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);
}
}
and this is the derived class
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");
}
}
When running Project1, the output turns out to be:
This is stuff
Coding project number one: stuff
Why does it call whichProject() in Project1 and not the one in Project? After all, isn't doSomething() a method in Project? or when there is a method in the base class inside of another method in the base class then the object to which the variable refers to still determines which method invocation will be called even though we are inside of another method?
Now, if we change the modifier of whichProject() to private so that the class now is
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);
}
}
the output becomes:
This is stuff
This is a random project stuff
so now the whichProject() method in Project is being called and not the one Project1 even though the variable refers to an object of Project1. In this case, I do not understand at all what is happening. An explanation for both situations (whichProject() with a public modifier and whichProject() with a private modifier) would be appreciated.