aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Which Access Modifier when override toString()? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Which Access Modifier when override toString()?" Watch "Which Access Modifier when override toString()?" New topic
Author

Which Access Modifier when override toString()?

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
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

Joined: Aug 26, 2001
Posts: 7610
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 ]

SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Which Access Modifier when override toString()?
 
Similar Threads
Important Question regarding Garbage Collection
hashcode question
Overriding with Exception
K&B - Erratum ?
equals and hashcodes method query