Unit 3 · OOP Concepts

3.1.7Static members and a complete program

Static vs instance members (brief preview)

An instance member belongs to each object. A static member belongs to the class and is shared by all objects (covered fully in 3.3.2).

Instance memberStatic member
One copy per objectOne copy for the whole class
Used through an object: b1.show()Used through the class: Math.sqrt(16)
Can use the object's attributes and thisCannot use instance attributes or this directly
Example: each book's titleExample: a counter of how many books exist

main is static because Java must be able to call it before any object exists. That is also why main cannot call show() directly: it must first create an object (b1) and then call b1.show().

Worked example: Complete program

Java
class Book {
    String title;
    double price;

    Book(String title, double price) {
        this.title = title;
        this.price = price;
    }

    double priceWithDiscount(double percent) {
        return price - (price * percent / 100);
    }

    void show() {
        System.out.println(title + " : Rs. " + price);
    }
}

public class Main {
    public static void main(String[] args) {
        Book b1 = new Book("Java Basics", 2000);
        Book b2 = new Book("OOP in Practice", 3500);
        b1.show();
        System.out.println(b2.priceWithDiscount(10));  // 3150.0
    }
}

Walking through the program

  1. Java starts at main. No Book objects exist yet.
  2. new Book("Java Basics", 2000) creates the first object. The constructor copies the arguments into the attributes, using this to tell them apart from the parameters. The reference is stored in b1.
  3. The same happens for b2, which gets its own, separate title and price.
  4. b1.show() runs show() for b1, so it prints Java Basics : Rs. 2000.0. (price is a double, so 2000 is shown as 2000.0.)
  5. b2.priceWithDiscount(10) works out 3500 − (3500 × 10 / 100) = 3150.0 and returns it. println then prints the returned value.

Notice the two styles of method: show() prints and returns nothing (void), while priceWithDiscount() returns a value and lets the caller decide what to do with it, here print it.

Where the code goes

In Java, each public class must be in a file with the same name: public class Main goes in Main.java. A file can contain other, non-public classes, which is why Book can sit in the same file here. In real projects, put each class in its own file (Book.java, Main.java). Every program needs exactly one starting point: public static void main(String[] args).

Try it: add a third book, call show() on it, then add a method boolean isExpensive() that returns true when the price is more than 3000. Print the result for each book.