In a java book I'm reading, a practice program takes the protected clone() method in the Object class and overrides it. When they do this tho, they expand the visibility modifier to public so it can be used in any package. I'm confused why this would need to be done though. If by definition, everything is a subclass of Object and a method is declared protected in the Object class. Wouldn't that mean every class would have access to it. What is the need to make the method public when overriding it? I'm confused.
Asked
Active
Viewed 61 times
0
-
1A object can not access the `protected` methods of another object outside of the package it's defined in – MadProgrammer Feb 12 '19 at 06:47
1 Answers
2
You need to override it as public because you may wish to call it from a third class. Let's assume you have a Base
class which has a subclass Child
that overrides the method clone. Now I may have a third class as below.
public class Third {
public void m1(Child c) {
Child d = c.clone();
}
}
Here, class, Third is calling clone method, hence it needs to be declared public to be called.

vavasthi
- 922
- 5
- 14
-
@Vinay Avasthi you forgot to mention that Third is in a different package compared to Child, and is not a childClass of Child – Stultuske Feb 12 '19 at 06:54