user6276737
user6276737

Reputation:

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

A static 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 Animal and create a static attribute called live (which makes sense because being live is a static attribute of Animal), then why it won't be for instances such as dog, human, but only the class Animal? They are all live too and here I can see instances are really sharing this static attribute live.

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.

Upvotes: 1

Views: 62

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95774

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?

Upvotes: 4

Related Questions