1

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.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • 1
    "which makes sense because being live is a static attribute of Animal" no it's not every animal should have its own life, no? Some reading: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html –  Jun 15 '16 at 05:26
  • If we're talking about living animals then they're all "live", aren't they? –  Jun 15 '16 at 05:29
  • So dogs are live, humans are live, and at the same time animal is live. –  Jun 15 '16 at 05:29

1 Answers1

4
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?

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251