Static vs Instance Members

static

Part of: Writing Classes

Two Kinds of Members A class can have instance members that belong to each object, and static members that belong to the class itself . The static keyword is the difference. - An instance variable has one copy per object . - A static variable (class variable) has one copy shared by all objects . After new Robot(); new Robot(); new Robot();, Robot.getCount() returns 3, while each robot's id is 1, 2, 3. Static Methods A static method belongs to the class and is called on the class name, not an object: Because a static method has no specific object, it cannot use this and cannot read instance variables directly, there is no single object to read them from. It can only touch static fields and its own parameters. Choosing Static or Instance Use the table of intent below: - If the data or behavior describes one object , make it an instance member. - If it describes the whole class or is a pure utility, make it static . Key points: - static members belong to the class ; instance members belong to objects . - One static variable is shared ; each instance variable is per object . - Static methods are called on the class name and cannot access instance variables or this.

Challenge: Count the Widgets