UML class diagrams
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
👋 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.
🦥 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.
🏛 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
💡Clase
💡Atributo
💡Método
💡Visibilidad
💡Herencia
💡Asociación
💡Agregación
💡Composición
💡Multiplicidad
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
Hi, my name is Bear, and today I'll be teaching you about UML class diagrams.
We'll start with some of the basic characteristics.
Then we'll talk about relationships
and finally we'll finish up by going through a few examples together.
All right, let's talk about some of the basic characteristics of class diagrams.
To help explain these characteristics, I'm going to make up an example
to help us illustrate.
So let's say we're building a system for a zoo.
And keep in mind, these examples I'm going to use probably wouldn't
ever find their way into an actual program, but humor me
as I use these concepts to make it easier to understand.
So in our zoo, we want to describe the different things that are in the system.
You represent these things through classes,
and a class is depicted with this shape here.
So what's in a zoo?
Well, a ton of animals.
So we can create a class for our animals.
To do that, you just write the name of the class in this top section.
If our class is animal, an instance of that class would be a specific animal.
So the question is, how would you go about
identifying each instance of that class?
You do that through attributes.
An attribute is a significant piece of data containing values
that describe each instance of that class.
They're also known as fields, variables or properties,
and they go in the middle section here.
So for our animal class, we could create attributes like name, id, and age.
That way we could identify a specific instance of the animal class like Ruth
id number 304, age 114.
These need to be formatted a certain way, though.
You'll start with visibility, which we'll talk about later.
The name of the attribute, beginning with a lowercase letter.
Then you follow it with a colon and the data type for the name.
We'd want to return a string
and we can format the other attributes the same way, except
that we'd want to return an integer, since these are numbers.
Now that we've got some attributes
for our animal class, we get to the bottom section here.
This is where you put methods which are also known as operations or functions.
Methods allow you to specify any behavioral features of a class.
So we might ask ourselves what are some different behaviors of this animal class?
Maybe we'd want to be able
to change our animals names, like Ruth should actually be called Rita.
So let's create a function called setName.
We can also create a method for eating since all of our animals eat.
Methods also need to be formatted a certain way.
You start with visibility, which we'll talk about next.
Then the method beginning with a lowercase letter.
Next, you put parentheses to signify the function you're going to program later.
You can also add variables and the data type in here,
but in most cases it's not really necessary.
We'll add visibility in parentheses to the eat method as well.
Now let's talk about visibility.
The visibility of an attribute or method sets the accessibility
for that attribute or method.
So right now we have a minus sign for all of these, which indicates
that each of these attributes and methods are private.
They can't be accessed by any other class or subclass.
The exact opposite is the plus sign, which means an attribute
or method is public and can be accessed by any other class.
Another visibility type is indicated by the hash,
which means an attribute or method is protected.
These can only be accessed by the same class or its subclasses.
And finally there's the tilde or the squiggly, as I like to call it.
This sets the visibility to package or default, which means it can be used
by any other class as long it’s in the same package.
But that one is rarely ever used.
In most cases, your attributes are going to be private
or protected, and methods are often public.
Let's quickly review these basics with another example.
Let's make a class for employee.
We could give an employee attributes like name,
employee ID,
phone number
and department.
We'll want all of these attributes to be private and we could create a simple
method like updating a phone number which we'll go ahead and set to public.
So you might have noticed that I'm using
a diagraming application to create these UML class diagrams.
The same principles apply if you're using pen and paper.
But a diagraming software makes it much easier.
The diagraming application that I'm using today is Lucidchart.
You can sign up for a free account with your email address
and then you'll be able to follow along as we make these class diagrams together.
So the next thing we'll need to cover
are the different relationships that exist between classes.
The first type of relationship that we'll describe is inheritance.
And I'm going to keep going with the zoo example
because it makes it easy to understand the logic of these relationships.
We'll get to a more
technical real world example just a little later.
Okay.
So inheritance, let's say, in our zoo, the only animals we have
are tortoises, otters and the lesser known but nonetheless amazing slow loris.
In our system, we want to distinguish each of them as their own class.
So we'll make three classes for a tortoise, otter, and slow loris.
Now, instead of duplicating attributes for name, id and age,
we can make these classes into subclasses of the animal class
by drawing open arrows like this.
This is an inheritance relationship.
We're saying that these subclasses inherit all the attributes
and methods of the superclass.
You could also use the terms child and parent class.
So our order class is going to inherit the attributes of name, age and ID.
And then we could also add an attribute specific to the otter like whisker length.
One of the advantages of inheritance is that if we wanted to change or add
an attribute for all animals, we wouldn't have to go in and make
that change to tortoise and then otter and then slow loris.
We just make the change to the animal class
and it applies across all of its subclasses.
in this scenario, we also have what's called abstraction.
Animal is an abstract class because in our system,
any time we want to instantiate one of our classes, it's
going to be a tortoise, otter, or slow loris.
We wouldn't instantiate the animal class itself.
The animal class is just a way to simplify things and keep the code dry
so you don't repeat yourself.
So to show that this is an abstract class,
we'll put the name in italics.
You could put the class name inside these things as well, but I prefer italics.
Okay.
Another type of relationship is association.
So if we had a class for sea urchin, we could draw an association
which is just depicted by a simple line between otter and sea urchin.
And we could say otter eats sea urchin.
There's no dependency between them.
It's just a basic association relationship, and it's pretty simple.
The next type of relationship is aggregation.
It's a special type of association that specifies a whole and its parts.
So to continue with our zoo example,
again, this is just to help explain the logic.
Let's create a new class for a group of tortoises.
A group of tortoises is called a creep.
So here's our creep class and it's got a relationship with tortoise.
Any of our zoo's tortoises could be part of a creep, but they don't have to be.
A tortoise could leave the group at any point and still exist on its own.
That type of relationship where a part can exist outside
the whole is aggregation, and we note it with an open diamond.
There's also a relationship where the part can't exist outside the whole.
That's called composition.
To illustrate this, I'm going to create a few new classes.
Let's just say we have several different visitor centers in our zoo,
and each of those visitor centers has a lobby and a bathroom.
Now, if one of our visitor centers was torn down, the lobby
and the bathroom of that visitor center would also be destroyed.
Those rooms couldn't exist apart from the visitor center that is contained in.
That’s composition.
When a child object wouldn't be able to exist without its parent object.
We note a composition relationship with a closed diamond.
Another important
concept when we talk about relationships in UML is multiplicity.
Multiplicity allows you to set numerical constraints on your relationships.
For example, let's say we want to specify
that our visitor centers are going to have just one lobby.
We simply write the number one here, meaning
there can be one and only one lobby per visitor center.
But for bathrooms, maybe we want to make it so that there's
at least one bathroom per visitor center.
But leave the option to have as many as you'd like.
We'd use this notation to denote one or many bathrooms.
Other types of multiplicity are 0 to 1, which is an optional relationship.
N representing the specific amount, which in our example was one,
but it could be any other number depending on your use case.
Zero to many.
One to many.
Or a specific range.
Hopefully our zoo examples have helped explain those concepts.
But I want to show you what a real world example would look like.
This is a UML class diagram for an online shopping cart.
And if you want to look at the diagram with me, just click the link.
In the top right corner,
you can
see that this system has several classes and relationships.
So let's walk through a couple of them.
We'll start with the user class.
It's got attributes for user ID, password, login status and register date.
You've got the different return types on the right and on the left.
The visibility which is set to private.
You can see how the values returned by those attributes
would specifically describe an instance of the user class.
Down below we have a public method of verify
log in returning a boolean and this makes sense.
Right? Methods are behaviors of a class.
So if you were to log into your user account,
there's a function in place that verifies your login credentials.
Let's move on to the customer class.
This arrow tells us that customer is a child of user,
so customer inherits all the attributes and methods of the user class.
And same thing for the administrator class.
Both of these inherit from user, but also have their own
specific attributes and methods
like administrator can update the catalog, but the customer can't.
Stemming from customer, there are also several lines with the closed end diamond.
So if you recall, these are composition relationships
which mean that the parts cannot exist without the whole.
in the instance of the customer class, if that customer’s account was destroyed,
his shopping cart would be destroyed as well and all of his orders would be lost.
They can't exist outside of the customer.
The same applies for the shipping info and order details.
If there's no order, there's not going to be any order details or shipping info.
The last thing we'll look at in this example is multiplicity.
You can see that a customer can have zero or many orders.
Makes sense, right?
You could create a customer account for an online store but never buy anything.
Or you could be a frequent customer and place several different orders.
And then on the flip side, an order can belong to only one customer.
It'd be pretty confusing if a specific order with a unique order ID
was duplicated across several different customers.
And here you can see a 1 to 1 relationship.
Each order has one and only one order details
and order details belongs to one and only one order.
Okay, that wraps up our tutorial for UML class diagrams.
If you're interested in learning more about diagraming, processes, systems
and organizations, visit training.lucid.co I hope to see you there.
Ver Más Videos Relacionados
Tutorial - Diagrama de Clases UML
CASO USO UML
Que es Programación Orientada a Objetos (POO)
Ingeniería del Software II - Modelado de clases con UML - Fernando Pereñiguez
🚀 MÉTODOS en JAVA | ¿Cómo crear un método? 🤔| POO con Java 🖥️ | Explicación FÁCIL 2023 | #3
🚀 MÉTODOS CONSTRUCTORES y OBJETOS en JAVA | 🤔| POO con Java 🖥️ | Explicación FÁCIL 2023 | #4
5.0 / 5 (0 votes)