Difference between instance variable and instances


#1

In the following Dog example, it states that we need a class constructor to add ‘Dog instances’, then a couple of sections after it says we need to add instance variables under the main “class dog” section.

What is the difference between ‘instances’ and ‘instance variables’. Can we not add ‘int age;’ under ‘public Dog() {’, .
See code below:

class Dog {
int age;
public Dog() {
}
public static void main(String[] args) {

}

}


#2

Instances of objects are cases where the objects are constructed:

Dog buddy = new Dog();

Instance variables are variables that store information for an instance of each object of a class:

public class Dog{
  private int age;
  ...
}

You wouldn’t want to declare your age variable inside the constructor, because it would be confined to that local scale, and unusable beyond that point.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.