Knowledge Transfer

Ethickfox kb page with all notes


Project maintained by ethickfox Hosted on GitHub Pages — Theme by mattgraham

Java Core

Object Oriented Programming

OOP - a programming methodology based on representing a program as a set of objects, each of which is an instance of a certain class, and the classes form an inheritance hierarchy. What are the limitations of OOP?

Encapsulation

Hiding the state and implementation of the class and providing a public API for interacting with the class and its instances.

Inheritance

a mechanism that allows you to build some classes on the basis of others (children based on parent classes), in which the child class inherits the behavior and state of the parent.

Multi-Inheritance

Originally, in Java we didn't have multi-inheritance so we didn’t face the diamond problem. With the emergence of default methods, the diamond problem may arise. Candidates may be asked what will happen if we have two unrelated interfaces that have a default method with the same signature and different implementation, and we want to implement these two interfaces in a class. the problem will arise at the compilation level, and will return a compilation error. One solution is to override this method in the class. Another option is to use composition: if you have one class that implements one interface, you can try to represent it as an inner class inside of another class.

Java does not support the multiple inheritance for classes, which means that a class can only inherit from a single superclass.

But you can implement multiple interfaces with a single class, and some of the methods of those interfaces may be defined as default and have an implementation. This allows you to have a safer way of mixing different functionality in a single class.

Polymorphism

the ability to identically use objects with the same interface without information about the specific type of this object

Abstraction

highlighting common characteristics and functionality of objects or systems, ignoring unnecessary details. Пример: Банковское приложение/автомобиль

Aggregation

the inner class can exist separately from the outer class.

Composition

внутренний класс полностью инкапсулирован внешним классом. Внешний мир не может получить ссылку на внутренний класс отдельно от внешнего. Он живет и умирает вместе с внешним - Inner Class

Advantages of composition before inheritance.

Inheritance lags behind composition in the following scenarios:

Delegation

перепоручение задачи от внешнего объекта внутреннему

Object

Класс, от которого неявно наследуются все объекты в Java

Methods

equals & hashCode

hashCode - метод для вычисления хэш функции. Дефолтная реализация зависит от jvm, может основываться на адресе объекта в памяти. При переопределении следует учитывать следующие правила:

@Override
public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof Money))
        return false;
    Money other = (Money)o;
    boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
      || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
    return this.amount == other.amount && currencyCodeEquals;
}

static

Статические поля или переменные инициализируются после загрузки класса в память. Статичный блок НЕ может пробросить перехваченные исключения, но может выбросить не перехваченные. В таком случае возникнет «Exception Initializer Error». На практике, любое исключение возникшее во время выполнения и инициализации статических полей, будет завёрнуто Java в эту ошибку. Это также самая частая причина ошибки «No Class Def Found Error», т.к. класс не находился в памяти во время обращения к нему.

Interface

Маркерный Interface

Интерфейс без методов, с помощью которого можно помечать другие классы, тем самым предоставляя доп информацию о классе. Например Serializible, Clonable

Функциональный Interface

Интерфейс с одним не реализованным методом. За исключением default и методов Object’a. Используется для лямбд.

Immutable objects

Immutable objects are those objects whose state can not be changed once created. Class whose objects possess this characteristic can be termed as immutable class.

Steps for creating an immutable class

Immutable classes thread safe

Immutable classes are thread safe because you can not change state of immutable objects, so even if two thread access immutable object in parallel, it won’t create any issue.

Immutable collections

Collections.unmodifiable* - wraps collection into unmodifiable, returns UnsupportedOperationException for editing operations and returns object itself in case of getting operations. So objects should be immutable too.

Типизация

Exceptions

Типы исключений

Обработка

Поймать исключение можно с помощью try-catch-finally. В случе если было выброшено исключение, поток, в котором оно выброшено завершает работу.

throws

Указывает, что метод может выбросить исключение. При наследовании можно добавлять uncheked, не указывать, либо сужать

try with resources

Новый вид try catch, который сам может закрывать ресурсы(если они наследуются от AutoCloseable), с которыми работал, вне зависимости от того, было ли исключение

finally

Блок выполняется всегда(кроме System.exit()).

Questions

OOP

Composition, and Aggregation help to build (Has - A - Relationship) between classes and objects. But both are not the same in the end. 

[!info] 11.7 Implementing the 'equals()', 'hashCode()', and 'compareTo()' Methods :: Chapter 11. Collections and Maps :: A programmer's guide to java certification :: Certification :: eTutorials.org
The majority of the non-final methods of the Object class are meant to be overridden.
http://etutorials.org/cert/java+certification/Chapter+11.+Collections+and+Maps/11.7+Implementing+the+equals+hashCode+and+compareTo+Methods/

Exceptions

Annotations