← العودة إلى الدورة: Java from scratch

Classes and objects

الفيديو قريبًا

We arrive at the central idea of Java: object-oriented programming (OOP). Until now you handled loose data (a name, an age, a balance) and methods that operated on them. In real life things combine data and behavior: a bank account has an owner and a balance, and knows how to deposit and withdraw money. A class is the blueprint that describes that combination; an object is a concrete thing created from that blueprint. From an Account class you can create a thousand different accounts, each with its own data.

Fields, constructor and methods

A class is made of fields (variables that hold the state of each object), a constructor (special code that runs when the object is created) and instance methods (the behavior). The constructor has the same name as the class and no return type. Inside the class, this refers to the current object; it is mainly used to tell a field from a parameter with the same name. Objects are created with new, and each one has its own copy of the fields. By convention, each public class goes in its own file with the same name; in these examples we put them all in one file so we can run it with java Main.java.

java
public class Main {
    public static void main(String[] args) {
        Dog rex = new Dog("Rex", 5);
        Dog luna = new Dog("Luna", 1);

        rex.bark();                          // Rex says: Woof!
        luna.birthday();
        System.out.println(luna.name + " is " + luna.age);   // Luna is 2
        System.out.println(luna.isPuppy());                  // false

        Dog same = rex;                      // same object, two names
        same.age = 10;
        System.out.println(rex.age);         // 10

        Dog nobody = null;
        System.out.println(nobody == null);  // true
        // nobody.bark();                    // would throw NullPointerException
    }
}

class Dog {
    String name;          // fields: the state of each dog
    int age;

    Dog(String name, int age) {      // constructor
        this.name = name;            // this.name is the field, name the parameter
        this.age = age;
    }

    void bark() {                    // instance method
        System.out.println(name + " says: Woof!");
    }

    void birthday() {
        age++;
    }

    boolean isPuppy() {
        return age < 2;
    }
}

References, null and toString

Class-type variables do not contain the object, but a reference to it. That is why Dog same = rex; does not create a new dog: now there are two names for the same object, and changing one changes the other. A reference can be null, which means it points to no object; calling a method on null causes NullPointerException, the most common Java error. If you print an object directly you get something unhelpful like Dog@1b6d3586; to show a readable text you override the toString method, which System.out.println uses automatically.

java
public class Main {
    public static void main(String[] args) {
        Account a = new Account("Ana");
        Account b = new Account("Luis", 100);
        a.deposit(50);
        System.out.println(a);                  // Ana: 50.0
        System.out.println(b.withdraw(30));     // true
        System.out.println(b.withdraw(500));    // false
        System.out.println(b);                  // Luis: 70.0
    }
}

class Account {
    String owner;
    double balance;

    Account(String owner) {
        this(owner, 0);              // calls the other constructor
    }

    Account(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }

    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    boolean withdraw(double amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }

    @Override
    public String toString() {
        return owner + ": " + balance;
    }
}
  • Forgetting new: Dog rex; only declares the variable (it is null); rex = new Dog(...) is missing.
  • Calling an instance method from main without an object: main is static and needs an object, such as rex.bark().
  • Two constructors with the same order of types cannot be told apart; remember the overloading rule.
  • If you write no constructor, Java creates an empty one; if you write one with parameters, the empty one disappears.
  • Comparing objects with ==: it compares references, not content; next week you will see equals.

اختبر ما تعلمته

السؤال 1 من 1

What is an object?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →