UML class diagrams

Lucid Software
10 Aug 202312:24

Summary

TLDREste tutorial detalla los diagramas de clases UML, explicando características básicas como atributos y métodos, y cómo se representan. Cubre visibilidad, con ejemplos de privada, pública, protegida y paquete. Explora relaciones entre clases como herencia, asociación, agregación y composición, con multiplicidad. Finaliza con un ejemplo real de un carrito de compras en línea, mostrando cómo se aplican estos conceptos en la programación.

Takeaways

  • 🐻 El video enseña sobre diagramas de clases UML, comenzando con las características básicas.
  • 🐘 Se usa el ejemplo de un sistema para un zoológico para explicar cómo funcionan las clases en UML.
  • 📦 Una clase representa una entidad en el sistema y contiene atributos (como nombre, id y edad) y métodos (como setName y eat).
  • 🔒 La visibilidad en UML define si los atributos y métodos son públicos (+), privados (-), protegidos (#), o por defecto (~).
  • 🧬 La herencia permite que las clases hijas hereden atributos y métodos de una clase padre, como el ejemplo de los animales del zoológico.
  • 🌀 La abstracción se utiliza para simplificar un sistema, haciendo que clases como 'Animal' sean abstractas y no se puedan instanciar.
  • 🔗 Las relaciones de asociación conectan clases sin crear dependencias, como la relación entre un 'otter' y un 'sea urchin'.
  • ⚙️ La agregación es un tipo de asociación en la que las partes pueden existir fuera del todo, mientras que la composición implica que las partes no pueden existir sin el todo.
  • ➕ La multiplicidad en UML define cuántas instancias de una clase pueden estar relacionadas con otra, como una o varias salas de baño por centro de visitantes.
  • 🛒 El ejemplo final muestra un sistema de carrito de compras en línea, donde las relaciones y la multiplicidad se aplican entre clases como 'User', 'Customer', y 'Order'.

Q & A

  • ¿Qué es un diagrama de clases en UML?

    -Un diagrama de clases en UML es una representación gráfica de las clases que forman parte de un sistema, mostrando sus atributos, métodos y las relaciones entre ellas.

  • ¿Cómo se representa una clase en un diagrama de clases?

    -Una clase se representa con un rectángulo dividido en tres secciones: el nombre de la clase en la parte superior, los atributos en el centro y los métodos en la parte inferior.

  • ¿Qué es un atributo en una clase y cómo se representa?

    -Un atributo es un dato que describe una instancia de una clase. Se representa con su nombre seguido de dos puntos y el tipo de dato que retorna. Por ejemplo, 'nombre: String' indica que el atributo nombre es de tipo cadena de texto.

  • ¿Qué es un método en una clase y cómo se formatea?

    -Un método es una función que define el comportamiento de una clase. Se formatea empezando con la visibilidad (por ejemplo, + para público o - para privado), seguido del nombre del método y los paréntesis. Puede incluir parámetros y su tipo de dato.

  • ¿Qué son la visibilidad y los símbolos que la representan?

    -La visibilidad indica el nivel de acceso de los atributos y métodos de una clase. Los símbolos son: '+' para público, '-' para privado, '#' para protegido y '~' para paquete o default.

  • ¿Qué es una relación de herencia en UML?

    -Una relación de herencia, o generalización, permite que una clase hija herede atributos y métodos de una clase padre. Se representa con una flecha abierta desde la clase hija hacia la clase padre.

  • ¿Qué es una clase abstracta y cómo se representa?

    -Una clase abstracta es una clase que no puede ser instanciada directamente, solo a través de sus subclases. Se representa colocando el nombre de la clase en cursiva.

  • ¿Qué es una relación de asociación y cómo se representa?

    -Una asociación es una relación simple entre dos clases. Se representa con una línea simple entre las clases. Por ejemplo, si una nutria come erizos de mar, se dibuja una línea entre 'nutria' y 'erizo de mar'.

  • ¿Qué es la agregación y cómo se distingue de la composición?

    -La agregación es una relación donde las partes pueden existir de forma independiente del todo, y se representa con un diamante abierto. En la composición, las partes no pueden existir sin el todo, y se representa con un diamante cerrado.

  • ¿Qué es la multiplicidad en UML y cómo se usa?

    -La multiplicidad especifica cuántas instancias de una clase pueden estar relacionadas con otra clase. Por ejemplo, '1' significa una instancia, '0..*' significa de 0 a muchas instancias. Se coloca junto a la línea que conecta las clases.

Outlines

00:00

👋 Introducción a los diagramas de clases UML

Bear presenta el tema de los diagramas de clases UML. Comienza explicando los conceptos básicos, relaciones entre clases y finaliza con ejemplos. Utiliza como ejemplo un sistema para un zoológico, introduciendo clases para representar objetos en el sistema como animales. Explica cómo se definen las clases, atributos y métodos, y cómo se relacionan entre sí. También menciona la importancia del formato y visibilidad de los atributos y métodos, que pueden ser privados, públicos, protegidos o por paquete.

05:02

🦥 Herencia y abstracción en el zoológico

Bear continúa con el ejemplo del zoológico para explicar la herencia entre clases. Define clases de animales específicos como tortugas, nutrias y el loris perezoso, que heredan atributos de la clase 'Animal'. Explica cómo los atributos y métodos de una clase padre son heredados por sus clases hijas, y cómo la abstracción simplifica el código al evitar la duplicación de atributos. También se introduce el concepto de relaciones de asociación y agregación, usando ejemplos como la relación entre una nutria y un erizo de mar.

10:04

🏛 Composición y multiplicidad en las relaciones

Bear detalla las relaciones de composición y multiplicidad. Explica cómo la composición indica que los objetos no pueden existir sin su clase principal, usando como ejemplo centros de visitantes que contienen lobbies y baños. También aborda la multiplicidad, permitiendo definir cuántas instancias de un objeto pueden existir en relación con otro. Se dan ejemplos de relaciones como 1 a 1 y 0 a muchos, ilustrando cómo se aplican en sistemas reales.

Mindmap

Keywords

💡Diagrama de clases UML

El diagrama de clases UML es una representación gráfica que muestra la estructura de un sistema, destacando sus clases, atributos, métodos y las relaciones entre ellas. En el video, se utilizan diagramas UML para explicar cómo se organiza la información y los comportamientos dentro de un sistema, como el ejemplo de un zoológico.

💡Clase

Una clase es una plantilla o modelo a partir del cual se crean objetos en un sistema. En el ejemplo del zoológico, 'Animal' es una clase que representa los animales en el sistema. Las clases contienen atributos (características) y métodos (comportamientos), y son un componente clave en los diagramas de clases UML.

💡Atributo

Un atributo es una propiedad o característica que describe a una instancia de una clase. En el diagrama de clases del zoológico, los atributos de la clase 'Animal' son 'nombre', 'id' y 'edad'. Estos atributos permiten identificar a un animal específico, como 'Ruth', con id 304 y edad 114.

💡Método

Un método, también llamado operación o función, define el comportamiento de una clase. En el video, el método 'setName' permite cambiar el nombre de un animal en el sistema, y 'eat' define el comportamiento de un animal cuando come. Los métodos permiten manipular y realizar acciones con los objetos de una clase.

💡Visibilidad

La visibilidad define el nivel de acceso a los atributos y métodos de una clase. En el video, se explican cuatro tipos de visibilidad: 'privado' (solo accesible dentro de la clase), 'público' (accesible desde otras clases), 'protegido' (accesible desde la misma clase y sus subclases) y 'por defecto' (solo accesible dentro del mismo paquete).

💡Herencia

La herencia es una relación entre clases donde una clase (subclase) hereda los atributos y métodos de otra clase (superclase). En el zoológico, 'Tortuga', 'Nutria' y 'Loris lento' son subclases que heredan de la clase 'Animal'. Esto permite reutilizar código y simplificar la estructura del sistema.

💡Asociación

La asociación es un tipo de relación entre clases que indica cómo interactúan entre sí sin una dependencia fuerte. En el video, se usa la asociación entre las clases 'Nutria' y 'Erizo de mar' para mostrar que las nutrias comen erizos, sin que una clase dependa completamente de la otra.

💡Agregación

La agregación es un tipo especial de asociación que indica una relación entre un todo y sus partes, donde las partes pueden existir de manera independiente. En el ejemplo del zoológico, una 'Creep' de tortugas puede incluir tortugas que también existen por separado. Se representa con un diamante abierto.

💡Composición

La composición es una relación más fuerte que la agregación, donde las partes no pueden existir sin el todo. En el ejemplo del zoológico, si un 'Centro de visitantes' es destruido, sus componentes (como el 'lobby' y el 'baño') también dejan de existir. Se representa con un diamante cerrado.

💡Multiplicidad

La multiplicidad establece las restricciones numéricas en una relación entre clases. Por ejemplo, un 'Centro de visitantes' tiene exactamente un 'lobby', pero puede tener uno o más 'baños'. Esto permite definir cuántos objetos de una clase pueden estar relacionados con otra clase.

Highlights

Introduction to UML class diagrams

Basic characteristics of class diagrams

Example of a zoo system to explain class diagrams

Definition and representation of a class

Explanation of attributes and their role in identifying class instances

Formatting attributes with visibility and data type

Introduction to methods and their behavioral significance

Formatting methods with visibility and function notation

Explanation of visibility levels: private, public, protected, package

Use case of private and public visibility for attributes and methods

Creating a class for employee with private attributes

Use of diagramming software like Lucidchart for UML class diagrams

Introduction to relationships between classes: inheritance

Example of subclassing in a zoo system with tortoises, otters, and slow lorises

Concept of inheritance and its advantages

Explanation of abstract classes and their representation

Introduction to association relationships

Aggregation relationship and its difference from association

Composition relationship and its notation with a closed diamond

Multiplicity in relationships and its different notations

Real-world example of an online shopping cart UML class diagram

Explanation of user, customer, and administrator classes in the shopping cart example

Illustration of composition relationships in customer's shopping cart and orders

Multiplicity in customer-orders relationship

Final thoughts and invitation to learn more about diagramming

Transcripts

play00:00

Hi, my name is Bear, and today I'll be teaching you about UML class diagrams.

play00:06

We'll start with some of the basic characteristics.

play00:09

Then we'll talk about relationships

play00:11

and finally we'll finish up by going through a few examples together.

play00:16

All right, let's talk about some of the basic characteristics of class diagrams.

play00:20

To help explain these characteristics, I'm going to make up an example

play00:24

to help us illustrate.

play00:26

So let's say we're building a system for a zoo.

play00:29

And keep in mind, these examples I'm going to use probably wouldn't

play00:33

ever find their way into an actual program, but humor me

play00:37

as I use these concepts to make it easier to understand.

play00:41

So in our zoo, we want to describe the different things that are in the system.

play00:46

You represent these things through classes,

play00:49

and a class is depicted with this shape here.

play00:53

So what's in a zoo?

play00:54

Well, a ton of animals.

play00:56

So we can create a class for our animals.

play00:58

To do that, you just write the name of the class in this top section.

play01:03

If our class is animal, an instance of that class would be a specific animal.

play01:08

So the question is, how would you go about

play01:11

identifying each instance of that class?

play01:14

You do that through attributes.

play01:17

An attribute is a significant piece of data containing values

play01:21

that describe each instance of that class.

play01:24

They're also known as fields, variables or properties,

play01:27

and they go in the middle section here.

play01:30

So for our animal class, we could create attributes like name, id, and age.

play01:36

That way we could identify a specific instance of the animal class like Ruth

play01:40

id number 304, age 114.

play01:44

These need to be formatted a certain way, though.

play01:46

You'll start with visibility, which we'll talk about later.

play01:49

The name of the attribute, beginning with a lowercase letter.

play01:52

Then you follow it with a colon and the data type for the name.

play01:57

We'd want to return a string

play01:59

and we can format the other attributes the same way, except

play02:03

that we'd want to return an integer, since these are numbers.

play02:06

Now that we've got some attributes

play02:07

for our animal class, we get to the bottom section here.

play02:11

This is where you put methods which are also known as operations or functions.

play02:16

Methods allow you to specify any behavioral features of a class.

play02:20

So we might ask ourselves what are some different behaviors of this animal class?

play02:25

Maybe we'd want to be able

play02:26

to change our animals names, like Ruth should actually be called Rita.

play02:31

So let's create a function called setName.

play02:34

We can also create a method for eating since all of our animals eat.

play02:38

Methods also need to be formatted a certain way.

play02:41

You start with visibility, which we'll talk about next.

play02:44

Then the method beginning with a lowercase letter.

play02:47

Next, you put parentheses to signify the function you're going to program later.

play02:52

You can also add variables and the data type in here,

play02:56

but in most cases it's not really necessary.

play02:59

We'll add visibility in parentheses to the eat method as well.

play03:04

Now let's talk about visibility.

play03:07

The visibility of an attribute or method sets the accessibility

play03:11

for that attribute or method.

play03:12

So right now we have a minus sign for all of these, which indicates

play03:16

that each of these attributes and methods are private.

play03:18

They can't be accessed by any other class or subclass.

play03:23

The exact opposite is the plus sign, which means an attribute

play03:26

or method is public and can be accessed by any other class.

play03:31

Another visibility type is indicated by the hash,

play03:34

which means an attribute or method is protected.

play03:37

These can only be accessed by the same class or its subclasses.

play03:41

And finally there's the tilde or the squiggly, as I like to call it.

play03:46

This sets the visibility to package or default, which means it can be used

play03:50

by any other class as long it’s in the same package.

play03:54

But that one is rarely ever used.

play03:56

In most cases, your attributes are going to be private

play03:59

or protected, and methods are often public.

play04:02

Let's quickly review these basics with another example.

play04:05

Let's make a class for employee.

play04:08

We could give an employee attributes like name,

play04:12

employee ID,

play04:14

phone number

play04:16

and department.

play04:17

We'll want all of these attributes to be private and we could create a simple

play04:22

method like updating a phone number which we'll go ahead and set to public.

play04:27

So you might have noticed that I'm using

play04:30

a diagraming application to create these UML class diagrams.

play04:34

The same principles apply if you're using pen and paper.

play04:37

But a diagraming software makes it much easier.

play04:41

The diagraming application that I'm using today is Lucidchart.

play04:45

You can sign up for a free account with your email address

play04:48

and then you'll be able to follow along as we make these class diagrams together.

play04:52

So the next thing we'll need to cover

play04:54

are the different relationships that exist between classes.

play04:57

The first type of relationship that we'll describe is inheritance.

play05:01

And I'm going to keep going with the zoo example

play05:03

because it makes it easy to understand the logic of these relationships.

play05:08

We'll get to a more

play05:09

technical real world example just a little later.

play05:12

Okay.

play05:12

So inheritance, let's say, in our zoo, the only animals we have

play05:17

are tortoises, otters and the lesser known but nonetheless amazing slow loris.

play05:23

In our system, we want to distinguish each of them as their own class.

play05:27

So we'll make three classes for a tortoise, otter, and slow loris.

play05:32

Now, instead of duplicating attributes for name, id and age,

play05:36

we can make these classes into subclasses of the animal class

play05:40

by drawing open arrows like this.

play05:43

This is an inheritance relationship.

play05:46

We're saying that these subclasses inherit all the attributes

play05:49

and methods of the superclass.

play05:51

You could also use the terms child and parent class.

play05:55

So our order class is going to inherit the attributes of name, age and ID.

play05:59

And then we could also add an attribute specific to the otter like whisker length.

play06:04

One of the advantages of inheritance is that if we wanted to change or add

play06:08

an attribute for all animals, we wouldn't have to go in and make

play06:11

that change to tortoise and then otter and then slow loris.

play06:16

We just make the change to the animal class

play06:18

and it applies across all of its subclasses.

play06:22

in this scenario, we also have what's called abstraction.

play06:26

Animal is an abstract class because in our system,

play06:29

any time we want to instantiate one of our classes, it's

play06:32

going to be a tortoise, otter, or slow loris.

play06:36

We wouldn't instantiate the animal class itself.

play06:38

The animal class is just a way to simplify things and keep the code dry

play06:42

so you don't repeat yourself.

play06:44

So to show that this is an abstract class,

play06:46

we'll put the name in italics.

play06:49

You could put the class name inside these things as well, but I prefer italics.

play06:54

Okay.

play06:54

Another type of relationship is association.

play06:57

So if we had a class for sea urchin, we could draw an association

play07:01

which is just depicted by a simple line between otter and sea urchin.

play07:05

And we could say otter eats sea urchin.

play07:08

There's no dependency between them.

play07:10

It's just a basic association relationship, and it's pretty simple.

play07:15

The next type of relationship is aggregation.

play07:18

It's a special type of association that specifies a whole and its parts.

play07:23

So to continue with our zoo example,

play07:25

again, this is just to help explain the logic.

play07:29

Let's create a new class for a group of tortoises.

play07:33

A group of tortoises is called a creep.

play07:35

So here's our creep class and it's got a relationship with tortoise.

play07:40

Any of our zoo's tortoises could be part of a creep, but they don't have to be.

play07:44

A tortoise could leave the group at any point and still exist on its own.

play07:49

That type of relationship where a part can exist outside

play07:52

the whole is aggregation, and we note it with an open diamond.

play07:56

There's also a relationship where the part can't exist outside the whole.

play08:01

That's called composition.

play08:03

To illustrate this, I'm going to create a few new classes.

play08:07

Let's just say we have several different visitor centers in our zoo,

play08:11

and each of those visitor centers has a lobby and a bathroom.

play08:15

Now, if one of our visitor centers was torn down, the lobby

play08:18

and the bathroom of that visitor center would also be destroyed.

play08:22

Those rooms couldn't exist apart from the visitor center that is contained in.

play08:27

That’s composition.

play08:29

When a child object wouldn't be able to exist without its parent object.

play08:33

We note a composition relationship with a closed diamond.

play08:38

Another important

play08:39

concept when we talk about relationships in UML is multiplicity.

play08:44

Multiplicity allows you to set numerical constraints on your relationships.

play08:48

For example, let's say we want to specify

play08:51

that our visitor centers are going to have just one lobby.

play08:54

We simply write the number one here, meaning

play08:56

there can be one and only one lobby per visitor center.

play09:00

But for bathrooms, maybe we want to make it so that there's

play09:03

at least one bathroom per visitor center.

play09:06

But leave the option to have as many as you'd like.

play09:09

We'd use this notation to denote one or many bathrooms.

play09:14

Other types of multiplicity are 0 to 1, which is an optional relationship.

play09:18

N representing the specific amount, which in our example was one,

play09:22

but it could be any other number depending on your use case.

play09:26

Zero to many.

play09:27

One to many.

play09:28

Or a specific range.

play09:31

Hopefully our zoo examples have helped explain those concepts.

play09:34

But I want to show you what a real world example would look like.

play09:38

This is a UML class diagram for an online shopping cart.

play09:42

And if you want to look at the diagram with me, just click the link.

play09:45

In the top right corner,

play09:47

you can

play09:48

see that this system has several classes and relationships.

play09:51

So let's walk through a couple of them.

play09:53

We'll start with the user class.

play09:55

It's got attributes for user ID, password, login status and register date.

play10:00

You've got the different return types on the right and on the left.

play10:04

The visibility which is set to private.

play10:07

You can see how the values returned by those attributes

play10:10

would specifically describe an instance of the user class.

play10:14

Down below we have a public method of verify

play10:16

log in returning a boolean and this makes sense.

play10:20

Right? Methods are behaviors of a class.

play10:23

So if you were to log into your user account,

play10:25

there's a function in place that verifies your login credentials.

play10:30

Let's move on to the customer class.

play10:32

This arrow tells us that customer is a child of user,

play10:35

so customer inherits all the attributes and methods of the user class.

play10:39

And same thing for the administrator class.

play10:41

Both of these inherit from user, but also have their own

play10:45

specific attributes and methods

play10:47

like administrator can update the catalog, but the customer can't.

play10:50

Stemming from customer, there are also several lines with the closed end diamond.

play10:55

So if you recall, these are composition relationships

play10:59

which mean that the parts cannot exist without the whole.

play11:02

in the instance of the customer class, if that customer’s account was destroyed,

play11:07

his shopping cart would be destroyed as well and all of his orders would be lost.

play11:12

They can't exist outside of the customer.

play11:15

The same applies for the shipping info and order details.

play11:18

If there's no order, there's not going to be any order details or shipping info.

play11:23

The last thing we'll look at in this example is multiplicity.

play11:26

You can see that a customer can have zero or many orders.

play11:30

Makes sense, right?

play11:31

You could create a customer account for an online store but never buy anything.

play11:37

Or you could be a frequent customer and place several different orders.

play11:41

And then on the flip side, an order can belong to only one customer.

play11:45

It'd be pretty confusing if a specific order with a unique order ID

play11:48

was duplicated across several different customers.

play11:52

And here you can see a 1 to 1 relationship.

play11:55

Each order has one and only one order details

play11:59

and order details belongs to one and only one order.

play12:04

Okay, that wraps up our tutorial for UML class diagrams.

play12:08

If you're interested in learning more about diagraming, processes, systems

play12:13

and organizations, visit training.lucid.co I hope to see you there.

Rate This

5.0 / 5 (0 votes)

Etiquetas Relacionadas
Diagramas UMLClases UMLRelaciones UMLMétodos y atributosHerencia UMLDiagrama de clasesLógica de sistemasVisibilidad de clasesAbstracciónAgregación y composición