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 . What usually goes wrong. What you see What caused it How to fix it --- --- --- non-static variable count cannot be referenced from a static context count is an instance variable but getCount is static Mark count static so a single copy belongs to the class The count is

Challenge: Count the Widgets