Object variables and class variables in Java
•
Java
I'm learning Java. I don't understand the difference between object variables and class variables All I know is that in order to make it a class variable, you must first declare it with a static statement@ H_ 419_ 2 @ Thank you!
Solution
In Java (usually OOP), objects have two types of fields (variables)
Instance variables (or object variables) are fields that belong to a specific instance of an object
Static variables (or class variables) are common to all instances of the same class
Here is an example:
public class Foobar{ static int counter = 0 ; //static variable..all instances of Foobar will share the same counter public int id; //instance variable. Each instance has its own id public Foobar(){ this.id = counter++; } }
Usage:
Foobar obj1 = new Foobar(); Foobar obj2 = new Foobar(); System.out.println("obj1 id : " + obj1.id + " obj2.id "= obj2.id + " id count " + Foobar.counter);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码