Arnob Arnob - 1 year ago 67
Java Question

Class instantiates instances,static is class specific, then why instances don't share static attribute?


attribute is class specific, to me that means it is only an attribute of the class.I know that instances use instance variables.My question is, If I, say create a class called
and create a static attribute called
(which makes sense because being live is a static attribute of Animal),then why it won't be for instances such as
, but only the class
? They are all live too and here I can see instances are really sharing this static attribute
.Please Don't give me Java definition or oracle document definition, I know all that.As a beginner I was wondering why it's not making sense in the literal terms.

Answer Source
class Animal {
  int age;

The above indicates that every instance of Animal including instances of Animal's subclasses has an age, and each one is separate: Animals can't see or affect one another's ages. Internally, when you call new Animal() or new Dog(), Java sets aside space in that instance for the age.

class Animal {
  static String kingdom = "Animalia";

This one, however, indicates that the class named Animal has a property, exactly one, and it's called Animal.kingdom. That kingdom property is available without an Animal instance, and (in a hierarchy where Dog extends Animal) it appears to be available as Animal.kingdom, Dog.kingdom, someAnimalInstance.kingdom, and someDogInstance.kingdom. However, all of these are provided as a courtesy: the official accessor is Animal.kingdom, and there's only ever one regardless of however many instances (including zero) you have of Animal or its subclasses.

Related: Why should the static field be accessed in a static way?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download