xSKILLby Infirals
Register

Java for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Classes and objects

Objects and text12 min readLesson 1 of 5

1.1 Classes describe objects

A class defines the fields and methods available on its objects. A field is a variable stored in each object. An object is one instance of the class with its own values for those fields. The class is the description; the object is the thing in memory that you use.

Create an object with new. Book book = new Book(); allocates a Book object and stores a reference to it in book. Access members with a dot: book.title reads a field, and book.describe() calls a method.

Class names usually use PascalCase, while fields and methods use camelCase. A class can live in the same file as Main as long as only one top-level class is public.

java
public class Main {
    public static void main(String[] args) {
        Book book = new Book();
        book.title = "Java Notes";
        book.pages = 220;
        System.out.println(book.title + " has " + book.pages + " pages");
    }
}

class Book {
    String title;
    int pages;
}

Output

Java Notes has 220 pages

1.1.1 Fields hold state

Instance fields are declared directly inside the class, outside any method. Each object gets its own copy. If you create two Account objects, changing the balance of one leaves the other unchanged.

Fields receive default values if no constructor assigns them: numeric fields become 0, booleans become false, and object references become null. Local variables in methods do not get defaults, which is why the compiler asks you to initialize them.

A method can read and change the fields of its own object. Calling counter.increment() runs the method with counter as the current object, so an unqualified field name such as value refers to that object's field.

java
public class Main {
    public static void main(String[] args) {
        Counter counter = new Counter();
        counter.increment();
        counter.increment();
        System.out.println(counter.value);
    }
}

class Counter {
    int value;

    void increment() {
        value++;
    }
}

Output

2

1.1.2 A class and its main method

The class that starts the program needs a main method. Helper classes usually do not. In a small example, Main can hold main while Book holds the data and behavior for a book.

A class with no constructor gets a default no-argument constructor from the compiler. That is why new Book() works even though the Book class in the example declares no constructor. Once you add a constructor of your own, the compiler stops providing the default one.

Methods in a helper class often run on an object: book.describe(). They do not need static, because they use the fields of the particular object that received the call.

1.1.3 References, aliasing, and null

A variable of a class type holds a reference to an object. Assigning one reference to another copies the reference, so both variables point to the same object. Changing a field through either variable is visible through the other. This is called aliasing.

The == operator on references asks whether they point to the same object. It does not compare field values. Once you write an equals method for a class, equals can compare content; without one, it inherits reference comparison from Object.

A reference can be null, which means it points to no object. Calling a field or method through null throws NullPointerException. Check for null before using a reference that might not have been set.

java
public class Main {
    public static void main(String[] args) {
        Box first = new Box();
        first.size = 10;
        Box second = first;
        second.size = 20;
        System.out.println(first.size);
        System.out.println(first == second);
    }
}

class Box {
    int size;
}

Output

20
true

1.1.4 Protect fields with encapsulation

Encapsulation means hiding a class's fields behind methods that control access. Mark fields private and provide public methods for the operations you want to allow. Other code then cannot assign an invalid balance directly.

A getter returns a field value. A setter or an operation such as deposit validates the new value before changing the field. A balance should not accept a negative deposit, and a withdrawal should not make the balance negative if that rule belongs to the class.

Private fields are still accessible to methods of the same class. That is how a public getter reads balance while outside code cannot. The class keeps its rules in one place, so checks are not repeated at every call site.

java
public class Main {
    public static void main(String[] args) {
        Wallet wallet = new Wallet();
        wallet.deposit(150);
        wallet.deposit(-20);
        System.out.println(wallet.getBalance());
    }
}

class Wallet {
    private int balance;
    void deposit(int amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    int getBalance() {
        return balance;
    }
}

Output

150

1.1.5 Static members belong to the class

A static field has one copy for the whole class. A static method runs without an object and cannot read instance fields directly. The main method is static because the launcher needs to call it before any object exists.

Use static for constants, utility methods, and counters that belong to the class as a whole. Instance fields describe one object's state and should stay non-static. Calling a static member through an object compiles, but ClassName.member shows the shared nature clearly.

A static counter can track how many objects a class creates. Each constructor can increment it, and every object sees the same value. Instance fields stay separate even when static fields are shared.

java
public class Main {
    public static void main(String[] args) {
        Settings first = new Settings();
        Settings second = new Settings();
        first.language = "English";
        second.language = "Hindi";
        Settings.launches++;
        Settings.launches++;
        System.out.println(first.language);
        System.out.println(second.language);
        System.out.println(Settings.launches);
    }
}

class Settings {
    static int launches;
    String language;
}

Output

English
Hindi
2

1.1.6 Practice

  1. Create a Rectangle class with width and height fields, then calculate its area from an object.
  2. Create two objects and change one field to confirm that each object keeps its own state.
  3. Make the fields private and add methods that set them only when both values are positive.
  4. Add a static counter that increases when a new rectangle is created. For now, increment the counter in main after each object is created.
  5. Create two references to one object, change a field through one reference, and print the field through the other.

For step 5, also test reference equality with == and print the result.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between a class and an object?

    A class is the definition of fields and methods. An object is one instance of that class with its own field values.

  • 02What does `null` mean for an object reference?

    It means the reference points to no object. Calling a method or reading a field through it throws `NullPointerException`.

  • 03When should a field or method be static?

    Use `static` when the member belongs to the class as a whole. A shared counter or a utility calculation is a common example.

Quiz

Check: Java classes and objects

Four questions on fields, object creation, default values and the default constructor.

4 questions

Question 1 of 4

0/4 answered

Which keyword creates a new object in Java?

Answer all you can, then submit.