SlideShare a Scribd company logo
2. Объекты
Программирование на Java
Федор Лаврентьев
МФТИ, 2016
Методы
Методы класса Object
• equals(), hashCode()
• clone()
• toString()
• finalize()
• wait(), notify(), notifyAll()
• getClass()
Декларация метода
class FileReader {
public String readEntireFile(String path, String name)
throws IOException;
Модификатор доступа
Имя
Класс-владелец
Список аргументов
Тип возвращаемого значения
Список исключений
Сигнатура метода
class FileReader {
public String readEntireFile(String path, String name)
throws IOException;
• Сигнатура = имя + список аргументов
Перегрузка метода
public String do() { ... }
public String do(String s) { ... }
public int do(Object obj) { ... }
public int do(int i) { ... }
public long do(int i) { ... }
Перегрузка метода
public String do() { ... }
public String do(String s) { ... }
public int do(Object obj) { ... }
public int do(int i) { ... }
public long do(int i) { ... } // WRONG!
Перегрузка метода - пример
public String do(String s) { ... }
public String do(int i) {
return do(Integer.toString(i));
}
public String do() {
return do(“Just do it”);
}
Инициализация объекта
Конструктор объекта
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public Animal() {
this.name = “Untitled animal”;
}
}
Animal a = new Animal(“Monkey”);
Конструктор объекта
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public Animal() {
this(“Untitled animal”);
}
}
Animal a = new Animal(“Monkey”);
Конструктор по умолчанию
public class Dog {
String name;
String breed;
int age;
}
Dog dog = new Dog();
System.out.println(dog.name);
dog.name = “Pooker”;
Конструктор по умолчанию
public class Dog {
String name = null;
String breed = null;
int age = 0;
public Dog() { /* do nothing */ }
}
Dog dog = new Dog();
System.out.println(dog.name); // null
dog.name = “Pooker”;
Значения по умолчанию
public class Dog {
String name = ”Nameless”;
String breed = “Mongrel”;
int age = 1;
}
Dog dog = new Dog();
System.out.println(dog.name); // ”Nameless”
System.out.println(dog.age); // 1
Final поля
public class Dog {
final String name;
final String breed;
}
Dog dog = new Dog();
dog.name = “Pooker”;
dog.breed = “Bloodhound”;
Final поля
public class Dog {
final String name;
final String breed;
} // WRONG!
Dog dog = new Dog(); // WRONG!
dog.name = “Pooker”; // WRONG!
dog.breed = “Bloodhound”; // WRONG!
Final поля
public class Dog {
final String name;
final String breed;
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
}
Dog dog = new Dog(“Pooker”, “Bloodhound”);
Final поля
pulic class Dog {
final String name;
final String breed;
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
public Dog(String name) {
this(name, “Mongrel”);
}
public Dog() {
this(“Nameless”);
}
}
Final объекты
class IntWrapper {
int i;
IntWrapper(int i) { this.i = i };
}
class FinalIntWrapper {
final IntWrapper wrapper = new IntWrapper(1);
...
wrapper = new IntWrapper(2);
}
Final объекты
class IntWrapper {
int i;
IntWrapper(int i) { this.i = i };
}
class FinalIntWrapper {
final IntWrapper wrapper = new IntWrapper(1);
...
wrapper = new IntWrapper(2); // WRONG
}
Final объекты
class IntWrapper {
int i;
IntWrapper(int i) { this.i = i };
}
class FinalIntWrapper {
final IntWrapper wrapper = new IntWrapper(1);
...
wrapper = new IntWrapper(2); // WRONG
wrapper.i = 3;
}
Final объекты
class IntWrapper {
int i;
IntWrapper(int i) { this.i = i };
}
class FinalIntWrapper {
final IntWrapper wrapper = new IntWrapper(1);
...
wrapper = new IntWrapper(2); // WRONG
wrapper.i = 3; // but right o_O
}
Стек инициализации объектов
class Tail {
int length;
Tail(int length) {
this.length = length;
}
}
class Head {
int teeth;
Head(boolean hasTeeth) {
teeth = hasTeeth ? DEFAULT_TEETH_COUNT : 0;
}
}
class Snake {
Tail tail;
Head head;
Snake(hasTeeth, length) {
this.tail = new Tail(length);
this.head = new Head(head);
}
}
Стек инициализации объектов
class Tail {
int length;
Tail(int length) { // 3
this.length = length; // 4
} // 5 – tail ready
}
class Head {
int teeth;
Head(boolean hasTeeth) { // 7
teeth = hasTeeth ? DEFAULT_TEETH_COUNT : 0; // 8
} // 9 – head ready
}
class Snake {
Tail tail;
Head head;
Snake(hasTeeth, length) { // 1
this.tail = new Tail(length); // 2
this.head = new Head(head); // 6
} // 10 – snake ready
}
Ловушка – незавершенная инициализация
class TeethCollector { ...
static void collect(Snake snake) { ... };
}
class Snake { ...
Snake(int length, boolean hasTeeth) {
tail = new Tail(length);
TeethCollector.collect(this);
head = new Head(hasTeeth);
}
}
Ловушка – незавершенная инициализация
class TeethCollector { ...
static void collect(Snake snake) { ... };
}
class Snake { ...
Snake(int length, boolean hasTeeth) {
tail = new Tail(length);
TeethCollector.collect(this); // WRONG!
head = new Head(hasTeeth);
}
}
Статические поля и методы
class Integer {
static final int MAX_VALUE = 2147483647;
static final String VALUE_NAME = “int32”;
static String toString(int i) { ... };
}
class Foo { ...
String s = Integer.VALUE_NAME + “ ” +
Integer.toString(Integer.MAX_VALUE));
}
Ловушка – порядок инициализации
class Utils {
static final String NAME = buildName(“a”);
static final String PREFIX = “utils_”;
static String buildName(String s) {
return PREFIX + s;
}
}
Ловушка – порядок инициализации
class Utils {
static final String NAME = buildName(“a”); // 1
static final String PREFIX = “utils_”; // 5
static String buildName(String s) { // 2
return PREFIX + s; // 3
} // 4
}
Ловушка – порядок инициализации
class Utils {
static final String NAME = buildName(“a”); // 1
static final String PREFIX = “utils_”; // 5
static String buildName(String s) { // 2
return PREFIX + s; // PREFIX = null! // 3
} // 4
}
Ловушка – цикл инициализации классов
class Foo {
static Bar BAR = new Bar();
static String NAME = “n”;
}
class Bar {
static String s = Nja.default();
}
class Nja {
static String default() { return Foo.NAME }
}
Ловушка – цикл инициализации классов
class Foo {
static Bar BAR = new Bar(); // 1
static String NAME = “n”; // 4
}
class Bar {
static String s = Nja.default(); // 2
}
class Nja {
static String default() { return Foo.NAME } // 3
}
Статические блоки инициализации
class NamedPerson {
static final String ABC;
static {
StringBuilder sb = new StringBuilder();
for (char c = ‘a’; c <= ‘z’; ++c) {
sb.append(c);
}
ABC = sb.toString();
}
}
Статические блоки инициализации не нужны
class NamedPerson {
static final String ABC = buildAbc();
static String buildAbc() {
StringBuilder sb = new StringBuilder();
for (char c = ‘a’; c <= ‘z’; ++c) {
sb.append(c);
}
return sb.toString();
}
}
Удаление объекта
Область видимости переменной
public String swarmBark() {
StringBuilder sb = new StringBuilder();
Dog pooker = new Dog(“pooker”);
sb.append(pooker.bark());
for (int i = 0; i < 10; ++i) {
Dog replier = new Dog(“Dog “ + i);
sb.append(replier.bark());
}
return sb.toString();
}
Деструкторы в Java
• Деструкторов нет
• Реакции на область видимости нет
• Есть сборщик мусора
Сборка мусора
• Терпи, пока память есть
• Найди* все** недостижимые*** объекты
• Вызови для каждого object.finalize()
• Удали их из памяти
Освобождение ресурсов
public void printFile(String fileName) [...] {
BufferedReader reader = new BufferedReader(
new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
Освобождение ресурсов (плохой пример)
public void printFile(String fileName) [...] {
BufferedReader reader = new BufferedReader(
new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close(); // ALL WRONG
}
Исключения
Исключения
public int modulo(int a, int b) {
int r = a % b;
if (r > 0 && a < 0) {
r -= n;
}
}
Исключения
public int modulo(int a, int b) {
// what if b == 0 ?
int r = a % b;
if (r > 0 && a < 0) {
r -= n;
}
}
Исключения
public int modulo(int a, int b) {
if (b == 0) {
throw new Exception(“Division by zero”);
}
int r = a % b;
if (r > 0 && a < 0) {
r -= n;
}
}
Исключения
public int modulo(int a, int b) {
if (b == 0) {
throw new DivisionByZeroException();
}
int r = a % b;
if (r > 0 && a < 0) {
r -= n;
}
}
Исключения
public int modulo(int a, int b)
throws DivisionByZeroException {
if (b == 0) {
throw new DivisionByZeroException();
}
int r = a % b;
if (r > 0 && a < 0) {
r -= n;
}
}
Иерархия исключений
http://www.ufthelp.com/2014/11/exception-handling-in-java.html
Ловля исключений
void touch(String name) throws IOException {...}
void refreshFile(String name) {
try {
touch(name);
} catch (FileNotFoundException e) {
// It’s ok, do nothing
} catch (EOFException|SyncFailedException e) {
e.printStackTrace();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
Finally
public void printFile(String fileName) [...] {
BufferedReader reader = new BufferedReader(
new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
Finally
public void printFile(String fileName) [...] {
BufferedReader reader = null;
try {
reader = new BufferedReader(
new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} finally {
reader.close();
}
}
Finally
public void printFile(String fileName)
throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(
new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} finally {
if (reader != null) reader.close();
}
}
Try-with-resources
public void printFile(String fileName)
throws IOException {
try (BufferedReader reader =
new BufferedReader(
new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
Try-with-resources
try (AutoCloseable closeable = ...) {
// Logic
} catch (Exception e) {
// Handle exceptions
} finally {
// Finish him
}
Finally и return
public String kickStudentsBrain(String s) {
try {
return s.toLowerCase();
} finally {
throw new IllegalStateException();
}
}
Finally и return
public String smashStudentsBrain(String s) {
try {
return s.toLowerCase();
} finally {
return s.toUpperCase();
}
}

More Related Content

PDF
Очень вкусный фрукт Guava
PDF
JavaScript. Loops and functions (in russian)
PDF
Tricky Java Generics
PDF
Красота и изящность стандартной библиотеки Python
ODP
Charming python sc2-8
PDF
8 встреча — Язык программирования Python (В. Ананьев)
PDF
Python и его тормоза
PDF
[JAM 1.1] Clean Code (Paul Malikov)
Очень вкусный фрукт Guava
JavaScript. Loops and functions (in russian)
Tricky Java Generics
Красота и изящность стандартной библиотеки Python
Charming python sc2-8
8 встреча — Язык программирования Python (В. Ананьев)
Python и его тормоза
[JAM 1.1] Clean Code (Paul Malikov)

What's hot (18)

PPT
Декораторы в Python и их практическое использование
PDF
Pyton – пробуем функциональный стиль
PDF
Лекция 5. Встроенные коллекции и модуль collections.
PPT
9. java lecture library
PDF
Лекция 1. Начало.
PDF
DevConf. Дмитрий Сошников - ECMAScript 6
PPTX
основы Java переменные, циклы
PPT
Быстрые конструкции в Python - Олег Шидловский, Python Meetup 26.09.2014
PPT
10. java lecture generics&collections
PDF
Лекция 2. Всё, что вы хотели знать о функциях в Python.
PDF
Лекция 4. Строки, байты, файлы и ввод/вывод.
PDF
Лекция 12. Быстрее, Python, ещё быстрее.
PDF
Монады для барабанщиков. Антон Холомьёв
PDF
Лекция 3. Декораторы и модуль functools.
ODP
Отладка в Erlang, trace/dbg
PDF
Лекция 8. Итераторы, генераторы и модуль itertools.
PPTX
Kotlin with API tests
PDF
Scala and LiftWeb presentation (Russian)
Декораторы в Python и их практическое использование
Pyton – пробуем функциональный стиль
Лекция 5. Встроенные коллекции и модуль collections.
9. java lecture library
Лекция 1. Начало.
DevConf. Дмитрий Сошников - ECMAScript 6
основы Java переменные, циклы
Быстрые конструкции в Python - Олег Шидловский, Python Meetup 26.09.2014
10. java lecture generics&collections
Лекция 2. Всё, что вы хотели знать о функциях в Python.
Лекция 4. Строки, байты, файлы и ввод/вывод.
Лекция 12. Быстрее, Python, ещё быстрее.
Монады для барабанщиков. Антон Холомьёв
Лекция 3. Декораторы и модуль functools.
Отладка в Erlang, trace/dbg
Лекция 8. Итераторы, генераторы и модуль itertools.
Kotlin with API tests
Scala and LiftWeb presentation (Russian)
Ad

Viewers also liked (13)

PPTX
Programming Java - Lection 01 - Basics - Lavrentyev Fedor
PPTX
Programming Java - Lection 03 - Classes - Lavrentyev Fedor
PPTX
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
PPTX
Industrial Programming Java - Lection Pack 02 - Distributed applications - La...
PPTX
Programming Java - Lection 05 - Software Design - Lavrentyev Fedor
PPTX
Programming Java - Lection 06 - Multithreading - Lavrentyev Fedor
PPTX
Industrial Programming Java - Lection Pack 01 - Building an application - Lav...
PPTX
Industrial Programming Java - Lection Pack 03 - Relational Databases - Lavren...
PPTX
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
PDF
Nómina de trabajadores portuarios beneficiarios
DOCX
Estructura 7
PPTX
Formularios y contenedores
Programming Java - Lection 01 - Basics - Lavrentyev Fedor
Programming Java - Lection 03 - Classes - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Industrial Programming Java - Lection Pack 02 - Distributed applications - La...
Programming Java - Lection 05 - Software Design - Lavrentyev Fedor
Programming Java - Lection 06 - Multithreading - Lavrentyev Fedor
Industrial Programming Java - Lection Pack 01 - Building an application - Lav...
Industrial Programming Java - Lection Pack 03 - Relational Databases - Lavren...
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Nómina de trabajadores portuarios beneficiarios
Estructura 7
Formularios y contenedores
Ad

Similar to Programming Java - Lecture 02 - Objects - Lavrentyev Fedor (20)

PPTX
Kotlin
PDF
Kotlin для Android
PPTX
Groovy и Grails. Быстро и обо всём
PPTX
PDF
Statis code analysis
PPTX
Bytecode
PDF
Школа-студия разработки приложений для iOS. Лекция 1. Objective-C
PPTX
[Expert Fridays] Java MeetUp - Борис Ташкулов (Teamlead Enterprise): "Почему ...
PDF
Об особенностях использования значимых типов в .NET
PPTX
C# Deep Dive
PPTX
C sharp deep dive
PPTX
Интерфейсы
PPTX
C++ осень 2012 лекция 11
PPTX
Зачем нужна Scala?
PDF
Kotlin на практике
PDF
Язык программирования Go для Perl-программистов
PDF
Ecma script 6 in action
PDF
Solit 2014, EcmaScript 6 in Action, Трухин Юрий
PDF
msumobi2. Лекция 1
PDF
msumobi2. Лекция 2
Kotlin
Kotlin для Android
Groovy и Grails. Быстро и обо всём
Statis code analysis
Bytecode
Школа-студия разработки приложений для iOS. Лекция 1. Objective-C
[Expert Fridays] Java MeetUp - Борис Ташкулов (Teamlead Enterprise): "Почему ...
Об особенностях использования значимых типов в .NET
C# Deep Dive
C sharp deep dive
Интерфейсы
C++ осень 2012 лекция 11
Зачем нужна Scala?
Kotlin на практике
Язык программирования Go для Perl-программистов
Ecma script 6 in action
Solit 2014, EcmaScript 6 in Action, Трухин Юрий
msumobi2. Лекция 1
msumobi2. Лекция 2

Programming Java - Lecture 02 - Objects - Lavrentyev Fedor