Класс и объект
Класс — шаблон, объект — его экземпляр. Класс описывает состояние (поля) и поведение (методы).
public class Car { String brand; int year; int speed; void accelerate(int delta) { speed += delta; } void printInfo() { System.out.println(brand + " " + year + ", скорость " + speed); }}public class Main { public static void main(String[] args) { Car car = new Car(); car.brand = "Toyota"; car.year = 2020; car.accelerate(60); car.printInfo(); Car other = new Car(); other.brand = "Lada"; other.printInfo(); }}Оператор new создает объект в куче и возвращает ссылку. Поля получают значения по умолчанию: 0, false, null.
Конструкторы
Конструктор вызывается при создании объекта. Имя совпадает с именем класса, возвращаемого типа нет.
public class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } Person(String name) { this(name, 0); } Person() { this("Без имени"); } void introduce() { System.out.println("Меня зовут " + name + ", мне " + age); }}public class Main { public static void main(String[] args) { new Person("Анна", 30).introduce(); new Person("Борис").introduce(); new Person().introduce(); }}Если конструкторов нет, компилятор создает пустой конструктор по умолчанию. Если вы объявили хотя бы один свой, конструктор по умолчанию не создается.
Ключевое слово this
this.поле— отличает поле от параметра с тем же именем;this(...)— вызов другого конструктора, только первой строкой;this— ссылка на текущий объект, можно передавать и возвращать.
public class Counter { private int value; Counter increment() { value++; return this; } int get() { return value; } public static void main(String[] args) { int result = new Counter().increment().increment().increment().get(); System.out.println(result); }}Блоки инициализации и порядок
Порядок создания объекта:
- значения по умолчанию;
- инициализаторы полей и блоки
{ }по порядку в коде; - тело конструктора.
public class InitOrder { int a = 1; { System.out.println("блок инициализации, a = " + a); } InitOrder() { System.out.println("конструктор"); } public static void main(String[] args) { new InitOrder(); }}Статические члены
Поле или метод с static принадлежат классу, а не объекту.
public class Account { private static int counter = 0; private final int id; static final double RATE = 0.05; Account() { id = ++counter; } int getId() { return id; } static int getCount() { return counter; } public static void main(String[] args) { new Account(); new Account(); Account third = new Account(); System.out.println(third.getId()); System.out.println(Account.getCount()); }}Статический метод не может использовать this и обращаться к нестатическим полям напрямую.
Статический блок выполняется один раз при загрузке класса:
public class Config { static final String VERSION; static { VERSION = "1.0"; }}Метод toString
По умолчанию println(object) выводит что-то вроде Person@1b6d3586. Переопределите toString:
public class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Point(" + x + ", " + y + ")"; } public static void main(String[] args) { System.out.println(new Point(3, 4)); }}equals и hashCode
== сравнивает ссылки. Чтобы сравнивать по содержимому, переопределяйте equals и всегда вместе с ним hashCode:
import java.util.Objects;public class Point { private final int x; private final int y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Point other)) { return false; } return x == other.x && y == other.y; } @Override public int hashCode() { return Objects.hash(x, y); } public static void main(String[] args) { Point a = new Point(1, 2); Point b = new Point(1, 2); System.out.println(a == b); System.out.println(a.equals(b)); System.out.println(a.hashCode() == b.hashCode()); }}Контракт: равные объекты обязаны иметь одинаковый hashCode. Без этого HashMap и HashSet работают неправильно.
Сборка мусора
Освобождать память вручную не нужно. Объект, на который не осталось ссылок, удаляется сборщиком мусора.
public class Garbage { public static void main(String[] args) { Object obj = new Object(); obj = null; }}Объект из примера становится недоступен и будет собран при очередном цикле сборщика.
Пакеты и импорт
Классы группируются в пакеты. Подключение чужого класса:
import java.util.ArrayList;import java.util.List;import java.util.*;Пакет java.lang, включая String, Math, Integer, подключается автоматически.
