Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overridding instance method with static method

 
sachin patel
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi i tried this
public class B {
public static String toString()
{
return "HI";
}
public static void main(String s[])
{
System.out.println(new B());
}
} //B class ends
when comiled::::::::::::::::
B.java:4: Instance methods can't be overridden by a static method.
Method java.lang.String toString() is an instance method in class java.lang.Obje
ct.
public static String toString()
^
1 error

can anyone explain me this
Thanks in advance....
------------------
Sachin,
****************************************************
Learn from others mistakes. Life is too short to make all yourself.
****************************************************
 
Pratap Reddy
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try to change your method to public String toString() instead of
public static String toString(). You can't override a instance method with a static method.
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vice-versa is also true. You cannot override a static method to be non-static.
Ajith
 
Ajay Patel
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler error is self-explanatory:
you simply cannot override an instance method with a static method. That is why you get the error.
The toString() method in class Object is defined as
public String toString()
and thus cannot be overriden with
public static String toString()
 
sachin patel
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much....
But i was just wondering if you can throw more light on this because i read this somewhere and i dont get it... may be little explanation will help....
Thanks in advance
------------------
Sachin,
****************************************************
Learn from others mistakes. Life is too short to make all yourself.
****************************************************
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic