JavaRush /Java Blog /Random EN /JAVA Object Oriented Programming Concepts
shabnahm
Level 18

JAVA Object Oriented Programming Concepts

Published in the Random EN group
JAVA is based on the concepts of object-oriented programming, which allows you to move to a higher level of abstraction to solve any problem in a realistic way. The object-oriented approach conceptualizes the solution to a problem in terms of real-world objects that are easier to reuse in an application. For example, Chair(chair), Fan(fan), Dog(Dog), Computer(computer) and so on. In JAVA, a class is a layout, template, or prototype that defines the general behavior of an object of a given type. An instance is a separate implementation of a class, and all instances of a class have the same properties, which are described in the class definition. For example, you can define a class named House with number of rooms as an attribute and create instances of the class such as a two-room house, a three-room house, and so on. JAVA Object Oriented Programming Concepts - 1Advantages: Listed below are some advantages of object-oriented software development.
  • Reduced software support costs, mainly due to the fact that it is carried out modularly.
  • Improved code reuse through features such as inheritance, resulting in faster software development.
  • Increased code reliability and flexibility.
  • Ease of understanding due to real world simulation.
  • Better abstraction at the object level.
  • Reducing the complexity of transition from one development phase to another.
There are four main characteristics of OOP:
  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

Encapsulation

Encapsulation acts as a contract for an object what it should hide and what it should open for access by other objects. In JAVA, we use an access modifier privateto hide a method and restrict access to a variable from the outside world. JAVA also has various access modifiers: public, default, protected, private, which are used to restrict visibility at different levels. But the ultimate goal is to encapsulate those things that shouldn't be changed. The approach that works best is that a class should only have one reason to change, and encapsulation makes the design of that “one reason” a reality. The correct approach to encapsulation is to hide things that change frequently to avoid damaging other classes. Benefits: Below are some of the benefits of encapsulation:
  • We can protect the internal state of an object by hiding its attributes.
  • This improves code modularity because it prevents objects from interacting in unexpected ways.
  • Improves code usability.
  • This supports the contractual relationship of a specific entity.
  • Encapsulation makes software easier to maintain.
  • Changes to the code can be made independently of each other.

Polymorphism

Polymorphism in programming is the ability to provide the same interface for different underlying forms (data types). This means that classes having different functionality share the same interface and can be called dynamically by passing parameters by reference. A classic example is the class Shape(shape) and all the classes that inherit from it: square(square), circle(circle), dodecahedron(dodecahedron), irregular polygon(irregular polygon), splat(blob), and so on. In this example, each class will have its own method Draw()and the client code can simply do:
Shape shape = new Shape();
Shape.area()to get the correct behavior of any shape The beauty of polymorphism is that the code, working with different classes, does not need to know which class it is using, since they all work on the same principle. The process used by object-oriented programming languages ​​to implement dynamic polymorphism is called dynamic binding. Note: Polymorphism is the ability to choose more specific methods to execute depending on the object. Polymorphism occurs when abstract classes are not involved. Advantages:
  • Creating reusable code. That is, once a class is created, implemented, and tested, it can be freely used without worrying about what exactly is written in it.
  • This allows for more generic and loosely coupled code.
  • Compilation time is reduced, which speeds up development.
  • Dynamic linking.
  • The same interface can be used to create methods with different implementations.
  • The entire implementation can be replaced by using the same method signatures.
Method overriding as part of polymorphism. An override interacts with two methods: a method in the parent class and a method in the derived class. These methods have the same name and signatures. Overriding allows you to perform the same operation in different ways for different types of objects. For example:
while(it.hasNext()) {
Shape s = (Shape) it.next();
totalArea += s.area(dim); //будет применен полиморфизм и вызван нужный метод для каждого an object.
}
JAVA Object Oriented Programming Concepts - 2Method overloading or ad-hoc polymorphism or static polymorphism Overloading interacts with multiple methods of the same class that are identically named but have different method signatures. Reloading allows you to describe the same operation in different ways for different data. It is sometimes called static polymorphism, but in fact it is not polymorphism. This is nothing more than simply having two methods with the same names, but a different list of arguments. Rebooting has nothing to do with inheritance and polymorphism. And an overloaded method is not at all the same as an overridden method. Parametric Polymorphism through Generication in JAVA When declaring a class, the name field can be associated with different types, and the method name can be associated with different parameters and return types. JAVA supports parametric polymorphism by using generics.
List<String> list = new ArrayList<String>();
Why can't we override a static method in JAVA? Overriding depends on the existence of an instance of the class. The idea of ​​polymorphism is that you can create a subclass, and the objects implemented by those subclasses will behave differently with the same methods of the parent class (overridden in the subclasses). A static method is not associated with any instances of the class, so the concept of overriding itself cannot be applied. The creators of JAVA were guided by two considerations that influenced this approach. First, there are code execution problems: there was a lot of criticism of Smalltalk for being slow (garbage collection and polymorphism were part of this problem), and JAVA was designed to avoid this. The second consideration was the decision that JAVA's target audience would be C++ developers. Having static methods work this way was very familiar to C++ programmers, and also speeded things up since there was no need to go up the class hierarchy to figure out which method to call. You go straight to the class and call a specific method.

Inheritance

Inheritance is the act of incorporating the behavior (i.e. methods) and state (i.e. variables) of a base class into a derived class so that they become available in that derived class. The main advantage of inheritance is that it provides a formal mechanism for code reuse and avoids duplication. An inherited class extends the functionality of the application by copying the behavior of the parent class and adding new functionality. This makes the code highly coupled. If you want to change the superclass, you will have to know all the details of the subclasses so as not to break the code. Inheritance is a form of software reuse where a new class (subclass) is created from an existing class (superclass) that extends its functionality and uses some of the properties of the superclass. So if you have a parent class and then a child class appears, the child inherits all the things that the parent has. Advantages:
  • Improved code reuse.
  • The logical relation “is a” (is someone, something) is established. For example: Dog is a n animal . (A dog is an animal).
  • Code modularization.
  • Repetitions are excluded.
Flaw:
  • Tightly coupled: A subclass depends on the implementation of a parent class, making the code tightly coupled.

Abstraction

Abstraction means designing classes based on their interfaces and functionality, without taking into account the implementation details. An abstract class represents interfaces without including the actual implementation. It distinguishes the implementation of an object from its behavior. Abstraction simplifies the code by hiding unimportant details. Advantages:
  • By using abstraction, we can separate out what can be grouped into some type.
  • Frequently modified properties and methods can be grouped into a separate type, so the main type will not be subject to changes. This reinforces the OOP principle: “Code should be open to Extension, but closed to Change . ”
  • Abstraction simplifies the representation of domain models.
Difference between abstraction and encapsulation Encapsulation is a strategy used as part of abstraction. Encapsulation refers to the structure of an object: objects encapsulate their properties and hide them from outside access. Users of a class interact with it using its methods, but do not have direct access to the class structure. In this way, the class abstracts implementation details related to its design. Abstraction is a more general term. It can also be achieved, among other things, using subclasses. For example, a class List(list) in the standard library is an abstraction for a sequence of elements, indexed according to their place in the list. Specific examples of a list Listare ArrayListor LinkedList. Code that interacts with a list Listabstracts away the details of which list it uses. Often abstraction is not possible without hiding the underlying state using encapsulation. If a class exposes its internal structure, it cannot change its internal operations, and therefore cannot be abstracted. What are abstract class and abstract method? It happens that during development you want a base class to only provide an interface to its derived classes. That is, you don't want anyone to create instances of the base class. You need to use the interface in such a way that you only cast objects to it (this is an implicit cast that allows polymorphic behavior). This is achieved by making this class abstract using the keyword abstract. This imposes some restrictions, such as the inability to create instances of an abstract class; when using an abstract class, it is necessary to implement abstract methods. This ensures polymorphism. An abstract class can contain both abstract and concrete methods. If at least one method in a class is declared abstract, the entire class must also be declared abstract. However, the rule in the opposite direction does not have to be observed. If a class is declared abstract, it may not contain abstract methods. A method that merely defines its signatures and does not provide an implementation is called abstract. Its actual implementation is left to its subclasses, which extend the abstract class. An abstract method cannot be used by an object, only another class can extend it. When should you use an abstract class? Abstract classes allow you to define some default behavior and have subclasses provide any specific behavior. For example: List(list) is an interface, in turn AbstractListdefines the basic behavior of a List, which can be used as is or refined in a subclass, for example, in ArrayList(list array). What is an interface? The concept of an interface is an abstract class, but the interface (defined by the keyword interface) goes one step further. It prevents any implementation of a method or function at all. You can only declare a method or function, but not provide its implementation. The class that implements the interface must take care of the actual implementation. Interfaces are very useful and are widely used in OOP. Since they share the interface itself and the implementation, they provide many advantages of their use:
  1. Multiple inheritance .
  2. Loose coupling . There is an abstraction of the operation, such as layering, and the concrete implementation can be anything: JDBC, JPA, JTA, etc.
  3. The interface program is not implemented .
  4. Dynamic binding polymorphism : The programming interface of an object is exposed without revealing its actual implementation.
  5. Abstract levels , separation of functionality.
Difference between interface and abstract class.
  • An interface is a contractual relationship with the classes that implement this interface, stating that the implementation occurs in the way designated by the interface. This is an empty shell with declared methods.
  • An abstract class defines some general behavior and asks its subclasses to define atypical or specific behavior for their class.
  • Methods and members of an abstract class can be designated with any access modifier; in turn, all interface methods must be public.
  • When inheriting an abstract class, the descendant class must define abstract methods, while an interface can inherit another interface without necessarily defining its methods.
  • A descendant class can extend only one abstract class, but an interface can extend or a class can implement many other interfaces.
  • A descendant class can define abstract methods with the same or less restrictive access modifier, but the class implementing the interface must define methods with the same level of visibility.
  • An interface does not contain constructors, while an abstract class does.
  • Variables declared in the Java interface are final by default. An abstract class can contain variables that are not final.
  • All members of the Java interface are public. Members of an abstract class can afford to be public, protectedetc.

Composition

Code reuse can be achieved using both inheritance and composition. But using composition provides a higher level of encapsulation than inheritance, since changes to the back-end class will not necessarily affect the code that belongs to the front-end class. Composition is a design technique that uses “has-a” (has, includes) relationships in classes. Both java inheritance and object composition can be used to reuse code. The essence of composition is to express the “has a” relationship between objects. Think about a chair. The chair has a seat. The chair has a back. A chair has a certain number of legs. The phrase “has a” suggests a relationship in which the chair has, or at least uses, another object. This is precisely the “has-a” relationship, which is the basis of the composition. Advantages:
  • Visibility control
  • The implementation can be replaced at run-time
  • Loose coupling, since the interface class does not depend on the implementation.
Differences between composition and inheritance
No. Composition (has a / has) Inheritance (is a / is)
1 Supports polymorphism and code reuse. Supports polymorphism and code reuse.
2 The run-time object has already been created. The object is created dynamically at compile time.
3 The implementation can be replaced at run-time. The implementation can be changed at compile time.
4 A subclass is independent of its parent class, which favors loose coupling (especially under interface control). The subclass is dependent on the implementation of the parent class, so the binding is considered strong.
5 Use: The House has a Bathroom. It is wrong to say that the House is the Bathroom. Inheritance is unidirectional: a House is a Building. But the building is not a home.
Note: Don't use inheritance just to ensure code reuse. If there is no relation “is a“ (is), composition is used for these purposes. The difference between composition and aggregation is in object relationships. Aggregation is a relationship in which one class fits into a collection. It is a part of a whole relationship, where a part can exist without the whole. Such relationships are much weaker. There is no cyclic dependency. For example: order and product. Composition is a relationship in which one class fits into a collection. It is a part of a whole relationship in which the part cannot exist without the whole. If the whole is destroyed, all its components will also be destroyed. It's a stronger relationship. For example: a polygon and its vertices, an order and its component.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION