• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overcome hiding method for static--pls help

 
Ann Sebastian
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Output::
The hide method in Animal.
The override method in Cat.

I want output to be
The hide method in Cat.
The override method in Cat.

Can this be done by retaining
1.static modifier for hide
2.Animal reference hold cat object

P.S. :This is just the replication of the problem I am facing in my project.
Please help.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods cannot be overridden like non-static methods.

It's bad practice to call a static method on an instance of a class. Static methods are class methods, i.e. they don't operate on a specific instance of the class, so it's confusing if you call it on an instance of a class. Instead of calling a static method on an instance, you should call it on the class itself, i.e.: Cat.hide() instead of myCat.hide().

If this is a problem for you in your project, you need to re-think the design of your software.
 
Ann Sebastian
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is I have 3 subclasses of animal and I need to dynamically access the hide method of subclass.The hide method is static.I use Factory Design Pattern to dynamicaly generate the subclass.Is there any way to do this?
 
Seb Mathe
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you really need hide method to be static ?
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ann Sebastian:
The problem is I have 3 subclasses of animal and I need to dynamically access the hide method of subclass.The hide method is static.I use Factory Design Pattern to dynamicaly generate the subclass.Is there any way to do this?


It sounds like hide() should NOT be static then. I don't think it is possible to get the behavior you want with a static method. (Well, there is a way using the Reflection API, but that is probably not what you are looking for.)

Layne
[ October 11, 2005: Message edited by: Layne Lund ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic