2

I'm beginner to java.I just recently learned about inheritance between classes. I know that if I inherit from a class,I can use those fields and methods,and also the objects I create will have those. But what about static fields and methods?

From what I tested,if I inherit a static field and change it(is not final),it will change also in parent class(and maybe in other ancestors).This is weird,or it's the way it should be?

It's like I have mammals and dolphins(and maybe other mammals).I want to know the number of dolphins,and the number of mammals to change when I add a dolphin.And this static field "nr" to be inherited.How can I get around this?

v.ladynev
  • 19,275
  • 8
  • 46
  • 67
  • There are [some good answer](http://stackoverflow.com/search?q=%5Bjava%5D+static+inheritance) on this topic –  Dec 27 '15 at 14:40
  • Regarding your problem, you could have some class (let's call it `AnimalFactory`) that creates and tracks animal instances –  Dec 27 '15 at 14:45
  • Yes,that could be helpful,and change numbers in AnimalFactory every time I use a constructor let's say. But also I could hide static variable "nr" in the new DOLPHIN class,even if it's not recommended. Maybe there are some reasons that I will learn in the future :) – Baltatu Andrei Mircea Dec 27 '15 at 14:52

0 Answers0