Posts

Showing posts from August, 2020

Can an object access a private member of a class in Java

Image
Inside the class, access to a private variable is open without restrictions; The nested class has full access to all (including private) members of the containing class; Access to private variables from the outside can be organized through methods other than private methods provided by the class developer. For example: getX() and setX(). Through the Reflection API: class Example { private int number = 54; } // ... Example example = new Example(); Field field = Example.class.getDeclaredField("number"); field.setAccessible(true); int fieldValue = (int) field.get(example); // ... Read also: What is Application Server How is an abstract class different from an interface in Java Concept of "interface" in Java

How is an abstract class different from an interface in Java

Image
In Java, a class can implement multiple interfaces at the same time, but inherit from only one class. Abstract classes are used only when the "is a" relationship type is present. Interfaces can be implemented by classes that are not related to each other. An abstract class is a tool for avoiding writing repetitive code, a tool for partially implementing behavior. An interface is a means of expressing the semantics of a class, a contract that describes capabilities. All interface methods are implicitly declared as public abstract or (since Java 8) default methods with a default implementation, and fields are public static final. Interfaces allow you to create structures of types without hierarchy. Inheriting from the abstract, the class “dissolves” its own individuality. By implementing an interface, it extends its own functionality. Abstract classes contain partial implementations that are augmented or extended in subclasses. Moreover, all subclasses are similar to eac...

What is Application Server

Image
Application Server (Application Server) - a program that is a server that deals with system support for applications and ensures their life cycle in accordance with the rules defined in the specifications. It can operate as a full-fledged stand-alone web server or be a page provider for another web server. Provides data exchange between applications and clients, assumes the implementation of such functions as creating a software environment for a functioning application, identifying and authorizing clients, organizing a session for each of them. The most famous Java application servers are: Apache Tomcat Jetty JBoss GlassFish IBM WebSphere Oracle Weblogic What is the difference between Web server and Application server The concept of a web server refers rather to a method of transferring data (specifically, over the HTTP protocol), while the concept of Application server refers to a way of executing these very applications (specifically, remote processing of client requests ...

Examples of behavioral design patterns

Image
Chain of responsibility - Designed for an organization within a system of levels of responsibility. Command - Represents an action. The command object contains the action itself and its parameters. Interpreter - Solves a frequently encountered but subject to change problem. Iterator - It is an object that allows you to get sequential access to the elements of an aggregate object without using the descriptions of each object included in the aggregation. Mediator - Enables many objects to interact while creating loose coupling and eliminating the need for objects to explicitly reference each other. Keeper (Memento) - Allows, without breaking the encapsulation, to fix and save the internal states of the object so that later it can be restored in these states. Observer - Defines a one-to-many dependency between objects so that when the state of one object changes, everyone that depends on it is notified of the event. State - It is used in cases when during program execution...

Examples of structural design patterns

Image
Adapter - An object that provides interaction between two other objects, one of which uses, and the other provides an incompatible interface with the first. Bridge - A structure that allows you to change the reference interface and the implementation interface of a class independently. Composite - An object that combines objects similar to itself. Decorator - A class that extends the functionality of another class without using inheritance. Facade - An object that abstracts the work with several classes, combining them into a single whole. Flyweight - This is an object that represents itself as a unique instance in different places in the program, but in fact it is not. Proxy - An object that mediates between two other objects, and which implements/restricts access to the object that is accessed through it. Read also: What is a Design Pattern Examples of basic design patterns Examples of generative design patterns

Examples of generative design patterns

Image
Abstract factory - A class that is an interface for creating other classes. Builder - A class that is an interface for creating a complex object. Factory method - Delegates the creation of objects to the heirs of the parent class. This allows you to use in the program code not specific classes, but to manipulate abstract objects at a higher level. Prototype - Defines the interface for creating an object by cloning another object instead of creating it through a constructor. Singleton - A class that can have only one instance. Read also: Types of design patterns What is a Design Pattern Examples of basic design patterns

Examples of basic design patterns

Image
Delegation pattern - An entity externally expresses some behavior, but in reality transfers responsibility for performing this behavior to a related object. Functional design - Ensures that each entity has only one responsibility and performs it with a minimum of side effects on others. Immutable interface - Creation of an immutable object. Interface - A general method for structuring entities to make them easier to understand. Marker interface - The presence or absence of an implementation of the marker interface is used as an attribute (as an entity tag). In modern programming languages, attributes or annotations are used instead. Property container - Allows you to add additional entity properties to the container within itself, instead of expanding with new properties. Event channel - Creates a centralized channel for events. Uses a proxy to subscribe and a proxy to post an event to a channel. The Representative is separate from the real publisher or subscriber. A subs...

Types of design patterns

Image
Fundamental are the basic building blocks of other templates. Most of the other templates use these templates in one form or another. Creational patterns are design patterns that abstract the instantiation process. They allow you to make the system independent of the way objects are created, composed and presented. The parenting template uses inheritance to modify the generated object, and the parenting template delegates the creation of objects to another object. Structural templates define various complex structures that change the interface of an existing object or its implementation, making it easier to develop and optimize a program. Behavioral patterns define the interaction between objects, thus increasing its flexibility. Read also: Where and what is the abstract modifier used for What is a Design Pattern Concept of "interface" in Java

What is a Design Pattern

Image
The design pattern is a proven and ready-to-use solution. This is not a class or a library that can be connected to the project, it is something more - it does not depend on the programming language, it is not a complete sample that can be directly converted into code and can be implemented in different ways in different programming languages. Pros of using templates: reducing the complexity of development due to ready-made abstractions for solving a whole class of problems. facilitating communication between developers by allowing reference to known patterns. unification of solution details: modules and project elements. the opportunity to find a good solution, use it again and again. assistance in choosing the most suitable design option. Minuses: blindly following some chosen pattern can complicate the program. a desire to try a certain pattern in action without any particular reason. What are the main characteristics of templates Name - all templates have a unique ...

Concept of "interface" in Java

Image
The interface keyword is used to create fully abstract classes. The main purpose of an interface is to determine how we can use the class that implements it. The interface creator defines method names, argument lists, and return types, but does not implement their behavior. All methods are implicitly declared as public. Since Java 8, interfaces are allowed to host the implementation of default methods and static methods. The interface can also contain fields. In this case, they are automatically public static final. Read also: Where and what is the abstract modifier used for What are the access modifiers in Java What does the final keyword say

Where and what is the abstract modifier used for

Image
A class marked with the abstract modifier is called an abstract class. Such classes can only act as ancestors for other classes. The abstract class itself is not allowed to be instantiated. In this case, both other abstract classes and classes that allow the creation of objects can be heirs of an abstract class. A method marked with the abstract keyword is an abstract method, i.e. a method that has no implementation. If there is at least one abstract method in the class, then the whole class must be declared abstract. Using abstract classes and methods allows you to describe a certain object template that must be implemented in other classes. They themselves describe only a certain behavior common to all descendants. Read also: How are JRE, JVM and JDK different What are the access modifiers in Java What does the final keyword say

Logical and bitwise operations and operators in Java

Image
Logical operations and operators & : Logical AND; && : Shorthand AND; | : Logical OR; || : Shorthand OR; ^ : Logical XOR (exclusive OR); ! : Logical unary NOT; &= : AND with assignment; |= : OR with assignment; ^= : XOR with assignment; == : Equal; != : Not equal; ?: : Ternary conditional operator. What is the ternary selection operator Ternary conditional operator ?: is an operator that can replace some constructions of if-then-else statements. The expression is written in the following form: condition ? expression1 : expression2 If the condition is met, then expression1 is evaluated and its result becomes the result of the entire statement. If the condition is false, then expression2 is evaluated and its value becomes the result of the operator's operation. Both expression1 and expression2 must return the same (or compatible) type. Bitwise operations ~ : Bitwise unary NOT operator; & : Bitwise AND; &= : Bitwise AND assignment; ...

Method main in Java

Image
The main() method is the entry point to the program. An application can have several such methods. If the method is absent, then compilation is possible, but at startup the error `Error: Main method not found` will be received. public static void main(String[] args) {} Read also: How are JRE, JVM and JDK different What are the access modifiers in Java What does the final keyword say

What values are the default variables initialized to

Image
Numbers are initialized to 0 or 0.0; char - \u0000; boolean - false; Objects (including String) - null. Read also: How are JRE, JVM and JDK different What are the access modifiers in Java What does the final keyword say

What does the final keyword say

Image
The final modifier can be applied to variables, method parameters, class fields and methods, or the classes themselves. The class cannot have descendants; The method cannot be overridden in inherited classes; The field cannot change its value after initialization; Method parameters cannot change their value inside a method; Local variables cannot be changed once a value has been assigned to them. Read also: How are JRE, JVM and JDK different What are the access modifiers in Java Execution Engine in JVM

What are the access modifiers in Java

Image
private : the members of the class are only accessible within the class. The service word private is used for designation. default, package-private, package level (package level access): Visibility of the class/class members only inside the package. This is the default access modifier - no special designation is required. protected : class members are available inside the package and in descendants. The service word protected is used for designation. public : the class/members of the class are available to everyone. The service word public is used for designation. A sequence of modifiers in ascending order of closeness: public, protected, default, private. During inheritance, it is possible to change access modifiers towards greater visibility (to maintain compliance with Barbara Liskov's substitution principle). Read also: How are JRE, JVM and JDK different Frames in JVM Execution Engine in JVM

How are JRE, JVM and JDK different

Image
JVM , Java Virtual Machine - the main part of the Java Runtime Environment (JRE). The Java Virtual Machine runs Java bytecode that is previously generated from the Java source by the Java compiler. The JVM can also be used to run programs written in other programming languages. JRE , Java Runtime Environment, is the minimum required virtual machine implementation to run Java applications. Consists of JVM and standard set of Java class libraries. JDK , Java Development Kit - JRE and a set of tools for developing applications in the Java language, including the Java compiler, standard Java class libraries, examples, documentation, various utilities. In short: JDK is an environment for developing programs in Java, which includes JRE - an environment for ensuring the launch of Java programs, which in turn contains a JVM - an interpreter for Java programs. Read also: Runtime data areas in Java Frames in JVM Execution Engine in JVM

Execution Engine in JVM

Image
The bytecode assigned to run-time data areas will be executed by the execution engine. The execution engine reads the bytecode and executes it piece by piece. Interpreter The interpreter interprets the bytecode quickly, but it is slow. The disadvantage of the interpreter is that when the same method is called multiple times, a new interpretation is required each time. JIT Compiler The JIT compiler eliminates the shortcomings of the interpreter. The engine will use the interpreter's help when converting the bytecode, but when it finds duplicate code, it uses a JIT compiler, which compiles all the bytecode and changes it to native code. This native code will be used directly for repeated method calls that improve system performance. Intermediate Code Generator. Produces intermediate code. Code Optimizer. Responsible for optimizing the intermediate code generated above. Target Code Generator. Responsible for generating machine code or native code. Profiler. A special componen...

Frames in JVM

Image
Frame is used to store data and partial results, as well as to perform dynamic binding, return values ​​for methods, and throw exceptions. A new frame is created every time the method is called. The Frame is destroyed when the method call completes, whether that completion is normal or abrupt (it throws an uncaught exception). Frames are popped off the stack of the thread creating the frame. Each frame has its own array of local variables, its own operand stack, and a reference to the constant pool during the execution of the current method's class. The sizes of the local variable array and operand stack are determined at compile time and provided with the code for the method associated with the frame. Thus, the size of the data structure, frame, depends only on the implementation of the Java virtual machine, and the memory for these structures can be allocated simultaneously when the method is called. Only one frame is active at any point in a given control flow, the execution me...

Runtime data areas in Java

Image
The JVM allocates many areas of data at runtime that are used at runtime. Some chunks of data are created by the JVM at startup and destroyed during shutdown. Others are created for each thread and destroyed when the thread is destroyed. The pc Register (PCR) The Java Virtual Machine can support many threads of execution concurrently. Each thread of the Java virtual machine has its own PC register (programm counter). At any time, each Java Virtual Machine thread is executing the code of one method, namely the current method for that thread. If this method is not native, the pc register contains the address of the Java virtual machine instruction that is currently executing. In short: there is one PCR for one thread, which is created when the thread starts. The PCR stores the address of the JVM instruction currently executing. Java Virtual Machine Stacks Each thread in the JVM has its own stack created at the same time as the thread. The stack in the JVM stores frames. Stacks in th...

Classloader in Java

Image
The class loader is the part of the JRE that dynamically loads Java classes into the JVM. Classes are usually only loaded upon request. The Java runtime doesn't need to know about files and file systems thanks to the class loader. Delegation is an important concept that the loader does. The class loader is responsible for finding libraries, reading their contents, and loading the classes contained in the libraries. This loading is usually done "on demand" because it does not happen until the program calls the class. A named class can only be loaded once by a given classloader. When the JVM starts up, three classloaders are used: Bootstrap class loader Extensions class loader System class loader The Bootstrap class loader loads the core Java libraries located in the <JAVA_HOME>/jre/lib folder. This loader is part of the core JVM, written in native code. The extension class loader loads the code into the extension directories (<JAVA_HOME>/jre/lib/ext,...

What the JVM is responsible for

Image
Loading, checking and executing byte code; Providing a runtime environment for executing bytecode; Memory management and garbage collection; The Java Virtual Machine is a mechanism that provides a runtime environment for managing Java code or applications. A virtual machine is an independent shell for executing code, thanks to which it can be launched on any OS, without the OS affecting the program being executed. JVM works with 2 data types: primitive types and reference types. Primitives The JVM works with primitive values ​​(integers and floats). Essentially, the JVM is a 32 bit machine. The types long and double, which are 64-bit, are natively supported but occupy two memory units in frame's local or operand stack, since each unit is 32 bits. The boolean, byte, short, and char types are signed wide (except for null-extended char) and work as 32-bit integers, just like int types. Smaller types have only a few type-specific instructions for loading, storing, and convertin...

What are static and dynamic binding

Image
Attaching a method call to the body of a method is called binding. If the binding is done by the compiler (linker) before starting the program, then it is called static or early binding . In turn, late binding is binding carried out directly at runtime, depending on the type of object. Late binding is also called dynamic or runtime binding . In languages ​​that implement late binding, there must be a mechanism for determining the actual type of an object at runtime to invoke the appropriate method. In other words, the compiler does not know the type of the object, but the method invocation mechanism determines it and calls the corresponding method body. Late-binding is language-specific, but it's not hard to assume that some additional information must be included in objects to implement it. All Java methods use late (dynamic) binding, unless the method has been declared final (private methods are final by default). Read also: Basic principles of OOP What is "encapsula...

What's the difference between composition and aggregation

Image
What do the expressions “is” and “has” mean in terms of OOP principles? "Is" implies inheritance. "Has" means an association (aggregation or composition). What's the difference between composition and aggregation? Association denotes a relationship between objects. Composition and aggregation are special cases of the “part-whole” association. Aggregation assumes that objects are connected in a "part-of" relationship. Composition is a stricter variant of aggregation. In addition to the “part-of” requirement, the condition is imposed that the “part” instance can only be included in one whole (or not included anywhere), while in the case of aggregation, the “part” instance can be included in several ones. For example, a book consists of pages, and we cannot rip a page out of a book and insert it into another book. Pages are clearly linked to a specific book, so this is composition. At the same time, we can take and transfer a book from one library to...

What are the advantages and disadvantages of an object-oriented approach to programming

Image
Benefits : The object model is quite natural, since it is primarily focused on the human perception of the world, and not on computer implementation. Classes allow you to construct from useful components with simple tools that abstract away from implementation details. Data and operations on them form a definite entity, and they are not spread throughout the program, as is often the case in procedural programming, but are described together. Localization of code and data improves the visibility and maintainability of software. Encapsulation allows you to introduce modularity, which makes it easier to parallelize the execution of a task across multiple workers and update versions of individual components. The ability to create extensible systems. Using polymorphism is useful when: Processing heterogeneous data structures. Programs can work without distinguishing the type of objects, which greatly simplifies the code. New species can be added at any time. Changes in behavior du...

Basic concepts of OOP: "class", "object", "interface"

Image
A class is a way to describe an entity, defining the state and behavior that depends on this state, as well as the rules for interacting with this entity (contract). From a programming point of view, a class can be viewed as a set of data (fields, attributes, class members) and functions for working with them (methods). From the point of view of program structure, a class is a complex data type. An object (instance) is a separate representative of a class with a specific state and behavior that is completely determined by the class. Each object has specific attribute values ​​and methods that operate on those values ​​based on the rules defined in the class. An interface is a collection of class methods available for use. The interface of a class will be a set of all its public methods together with a set of public attributes. Basically, an interface specifies a class, clearly defining all possible actions on it. Read also: Basic principles of OOP What is "encapsulatio...

What is messaging in OOP

Image
Objects interact by sending and receiving messages. A message is a request to perform an action, followed by a set of arguments that may be needed when performing an action. In OOP, sending a message (calling a method) is the only way to transfer control to an object. If an object is to "reply" to this message, then it must have a method corresponding to the message. Also, objects, using their methods, can themselves send messages to other objects. Messaging is done with dynamic calls, resulting in extreme late binding. Let's say you want to create a physical model describing colliding balls of different sizes. The traditional approach to solving this problem is approximately the following: a set of data describing each ball (for example, its coordinates, mass and acceleration) is determined; each ball is assigned a unique identifier (for example, an array is organized, the index value of which corresponds to the ball number), which will distinguish each of the balls fro...

What is "abstraction" in OOP

Image
Abstraction is a way to highlight a set of general characteristics of an object, excluding private and insignificant ones from consideration. Accordingly, abstraction is a collection of all such characteristics. Imagine that a driver is driving through a busy traffic area. It is clear that at this moment he will not think about the chemical composition of the paint of the car, the peculiarities of the interaction of the gears in the gearbox or the influence of the body shape on the speed (unless the car is in a dead traffic jam and the driver has absolutely nothing to do). However, he will use the steering wheel, pedals, turn signal regularly. Example: // Abstract class abstract class Animal { // Abstract method (does not have a body) public abstract void animalSound(); // Regular method public void sleep() { System.out.println("Zzz"); } } // Subclass (inherit from Animal) class Pig extends Animal { public void animalSound() { ...