Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Which Access Modifier when override toString()?

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
when I override the toString() method, why does the overridden toString method have to have the
PUBLIC ACCESS MODIFIER?

=======================================================================

C:\Java\EigeneJavaProgramme>javac Test24.java
Test24.java:5: toString() in Test24 cannot override toString() in java.lang.Object;
attempting to assign weaker access privileges; was public
String toString() {return "Object"+ i;}
===========================================================
COMPILES without ERROR IF overridden toString() method is PUBLIC
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because an overriding method cannot provide less access than the overridden method. Please read JLS 8.4.6.3 Requirements in Overriding and Hiding for more detailed information.

The access modifier (�6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs. In more detail:
-If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
- If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
- If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.

[ August 21, 2002: Message edited by: Valentin Crettaz ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic