JavaRush /Java Blog /Random EN /Relations between classes. Inheritance, composition and a...

Relations between classes. Inheritance, composition and aggregation

Published in the Random EN group
Hello! Today we will take a closer look at another principle of object-oriented programming (OOP) - inheritance. At the same time, we will study other types of relationships between classes - composition and aggregation. This topic will not be difficult: you have already come across inheritance and its examples many times in past lectures. Today, the main thing will be to consolidate your knowledge, consider the mechanism of inheritance in more detail and go over the examples again :) So, let's go!
Relations between classes.  Inheritance, composition and aggregation - 1

Inheritance in Java and its benefits

As you probably remember, inheritance (inheritance) is a mechanism that allows you to describe a new class based on an existing (parent) class. In this case, the properties and functionality of the parent class are borrowed by the new class. Let's recall the example of inheritance from the previous lectures:
public class Car {

   private String model;
   private int maxSpeed;
   private int yearOfManufacture;

   public Car(String model, int maxSpeed, int yearOfManufacture) {
       this.model = model;
       this.maxSpeed = maxSpeed;
       this.yearOfManufacture = yearOfManufacture;
   }


public void gas() {
       //...gas
   }

public void brake() {
       //...brake
   }
}


public class Truck extends Car {

   public Truck(String model, int maxSpeed, int yearOfManufacture) {
       super(model, maxSpeed, yearOfManufacture);
   }
}



public class Sedan extends Car {
   public Sedan(String model, int maxSpeed, int yearOfManufacture) {
       super(model, maxSpeed, yearOfManufacture);
   }
}
There is a certain program within which we work with different types of cars. Even if you are not a car enthusiast, you probably know that there are a great many types of these same cars in the world :) Therefore, we separate the general properties of cars into a common parent class - Car. And what do all cars have in common, regardless of type? Any car has a year of manufacture, a model name and a maximum speed. We put these properties in the fields model, maxSpeed, yearOfManufacture. As for the behavior, any car can accelerate and slow down :) We define this behavior in the methods gas()and brake(). What benefits does this give us? First of all, the reduction in the amount of code. Of course, we can do without the parent class. But since every car must be able to accelerate and brake, we will have to create methodsgas()and brake()in the class Truck, in the class Sedan, in the class F1Car, in the class, Sportcarand in all other classes of machines. Imagine how much extra code we will write in this case. Don't forget about the model, maxSpeed ​​and yearOfManufacture fields: if we drop the parent class, we'll create them in each of the machine classes! Relations between classes.  Inheritance, composition and aggregation - 2 When we have a couple dozen machine classes, the amount of repetitive code will become really serious. Moving common fields and methods (also called “states” and “behaviors”) into the parent class will save us a lot of time and space. If some type has properties or methods that are unique only to it and absent from other types of machines, it does not matter. They can always be created in a descendant class, separate from all others.
public class F1Car extends Car {

   public void pitStop() {

       //...only racing cars make pit stops
   }

   public static void main(String[] args) {

       F1Car formula1Car = new F1Car();
       formula1Car.gas();
       formula1Car.pitStop();
       formula1Car.brake();
   }
}
Take the case of Formula One racing cars. They, unlike the "relatives", have a unique behavior - from time to time they call in for a pit stop. It doesn't bother us. We have already described the general behavior in the parent class Car, and the specific behavior of descendant classes can be added inside classes. Relations between classes.  Inheritance, composition and aggregation - 3 This also applies to fields: if a child class has unique properties, we calmly declare these fields inside it and don’t worry :) The ability to reuse code is the main advantage of inheritance. It is very important for a programmer not to write an extra amount of code. You will encounter this many times at work. Please remember one more very important thing: there is no multiple inheritance in Java.Each class inherits from only one class. We will talk about the reasons for this in more detail in future lectures, for now just remember. Java, by the way, differs from some other OOP languages ​​in this way. For example, C++ has multiple inheritance. With inheritance, everything is more or less clear - let's move on.

Composition and aggregation

Classes and objects can be related to each other. Inheritance describes the relationship "is" (or in English "IS A"). The Lion is an Animal. Such a relationship is easy to express using inheritance, where Animalit will be the parent class, and Lionthe descendant. However, not all relationships in the world are described in this way. For example, the keyboard is definitely related to the computer in some way, but it is not a computer . Hands are somehow connected with a person, but they are not a person. In these cases, it is based on a different type of relationship: not "is", but "is a part" ("HAS A"). The hand is not a person, but is part of a person. The keyboard is not a computer, but is part of a computer. HAS A relationships can be described in code using the mechanisms of composition andaggregation . The difference between them lies in the "strictness" of these connections. Let's give a simple example: We have ours Car- a car. Every car has an engine. In addition, each car has passengers inside. What is the fundamental difference between fields Engine engineand Passenger [] passengers? If a passenger is sitting inside the car , this does not mean that passengers and Аcannot be in it . One car can fit multiple passengers. In addition, if all passengers are dropped out of the car, it will continue to function smoothly. The association between a class and an array of passengers is less strict. It's called aggregation . There is a good article on this topic: Relationships between classes (objects)BCCarPassenger [] passengers. It provides another good example of aggregation. Let's say we have a class Studentdenoting a student and a class StudentsGroup(a group of students). A student can be a member of a physics club, a Star Wars student fan club or a KVN team. Composition is a stricter type of relationship. With composition, an object is not only part of an object, but it cannot belong to another object of the same type. The simplest example is a car engine. The engine is part of a car, but cannot be part of another car. As you can see, their connection is much more strict than that of Carand Passengers. Relations between classes.  Inheritance, composition and aggregation - 4
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION