Most fields belong to each object. But a static field belongs to the class itself, and is shared by every object. It's like a single noticeboard everyone can see.
Sold is static, so there's only one, shared by all tickets. Number is a normal field, so each ticket has its own. The constructor adds one to sold, and gives the ticket its number. Price with tax is a static method. It doesn't need any ticket, just a price.
Main.javajava
public class Ticket { static int sold = 0; int number; Ticket() { sold++; number = sold; } static double priceWithTax(double price) { return price * 1.2; }}
We make three tickets. Each one gets the next number. Static members are used with the class name, Ticket dot sold. Math dot sqrt is static too. That's why we never wrote new Math. Run it. Tickets one, two, three. Three sold, and the price with tax is twelve.
Main.javajava
public class Main { public static void main(String[] args) { Ticket a = new Ticket(); Ticket b = new Ticket(); Ticket c = new Ticket(); System.out.println("Numbers: " + a.number + ", " + b.number + ", " + c.number); System.out.println("Sold in total: " + Ticket.sold); System.out.println("Price: " + Ticket.priceWithTax(10)); System.out.println("Square root of 81: " + Math.sqrt(81)); }}
Output
Numbers: 1, 2, 3
Sold in total: 3
Price: 12.0
Square root of 81: 9.0
Also uses Ticket.java
public class Ticket { static int sold = 0; int number; Ticket() { sold++; number = sold; } static double priceWithTax(double price) { return price * 1.2; }}
Instance members belong to each object, and need an object to use them. Static members belong to the class, and are used with the class name. Main is static, so Java can run it without creating any object first.
Instance
One per objectobj.method()Uses the object's fields
Static fields are shared by every object, and static methods need no object. Use them with the class name. Next, controlling who can see what, with access modifiers.