Why changing the access modifier of getname method changed the output we get Please explain..
I passed the test but doesn't understand how?
Resolved
Comments (7)
- Popular
- New
- Old
You must be signed in to leave a comment
Roman
22 October 2019, 11:23
Give an example (code) please
0
Brandon Horvatic
29 October 2019, 15:46solution
When access modifier of public String getName() is private, it returns "main", but when changed to public it returns "sout".
Why is that?
+5
Seb
18 January 2020, 19:53
The answer to that question is a little tricky. It can be found in the previous lesson though.
We are actually creating an anonymous derived class - and we are inheriting from the Solution class.
When we are calling new Solution("main").sout() in the main method, the getName method in the anonymous class calls the private getName method of the outer Solution class, which will return "main".
As soon as we change the getName method to protected or public, it can be inherited, and now the anonymous class has its own getName method, which can access it's own name field, which was set to "sout" in the constructor call.
I hope it kind of makes sense to you. I feel it's not that easy to explain.
+24
Johannes
3 May 2020, 05:10
lol, thanks Seb, but No: it doesn't make sense in the lesson, and it makes less sense in the example. To instantiate a new solution, I have to do it twice now. Once in main(), and another time in sout() ? Also, I am calling the method printName() two times ? Makes zero sense. As if starting with classes from scratch, and all old rules are out the window.
+1
Michal
3 June 2020, 19:07
All of this is really super unclear - no explanations for us too :/
+3
Johannes
4 June 2020, 05:46
yeah. Get used to it....
At least there are a couple of very helpful guys on the course, who'll assist if you ask them. Seb, Guadalupe, and others. Thnks
+3
Banak
21 March 2021, 22:38
new Solution("sout") {
void printName() {
System.out.println(getName());
}
}.printName();
This is a nested class, so the compiler has to handle two objects (one from Solution and one from the anonymous class) so the choice is made by modifying the access of the Solution class and specifying (this) to use the GetName method of the anonymous object. For my part, I think that the anonymous object can have access to the getName method whether it is public or private. Still it is my opinion... If someone has a better answer I take .
0