*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes overridding instance method with static method 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 "overridding instance method with static method" Watch "overridding instance method with static method" New topic
Author

overridding instance method with static method

sachin patel
Ranch Hand

Joined: Nov 28, 2000
Posts: 75
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.
****************************************************


Sachin,<P>****************************************************<BR>Learn from others mistakes. Life is too short to make all yourself.<BR>****************************************************
Pratap Reddy
Ranch Hand

Joined: Jan 05, 2001
Posts: 36
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

Joined: Mar 17, 2000
Posts: 5782
Vice-versa is also true. You cannot override a static method to be non-static.
Ajith


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Ajay Patel
Ranch Hand

Joined: Jan 02, 2001
Posts: 39
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

Joined: Nov 28, 2000
Posts: 75
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.
****************************************************
 
Consider Paul's rocket mass heater.
 
subject: overridding instance method with static method
 
Similar Threads
creating object using newInstance() method
More on the String
Dan's GC Question Doubt
Wrapper Class Object Doubt
toString()?