Clases
## Objetivos de Aprendizaje
- Definir clases y crear objetos
- Trabajar con constructores
- Comprender constructores factory
- Dominar miembros estaticos
- Aprender enums y extensiones
## Definiendo Clases
### Clase Basica
```dart
class Person {
String name = '';
int age = 0;
void greet() {
print('Hola, soy $name');
}
}
void main() {
var person = Person();
person.name = 'Alice';
person.age = 30;
person.greet();
}
```
### Clase con Constructor
```dart
class Person {
String name;
int age;
Person(this.name, this.age);
void greet() {
print('Hola, soy $name');
}
}
void main() {
var person = Person('Alice', 30);
person.greet();
}
```
## Constructores
### Constructor por Defecto
```dart
class Point {
double x = 0;
double y = 0;
}
void main() {
var p = Point();
print('${p.x}, ${p.y}'); // 0, 0
}
```
### Constructor Parametrizado
```dart
class Point {
double x;
double y;
Point(this.x, this.y);
}
void main() {
var p = Point(3, 4);
print('${p.x}, ${p.y}'); // 3, 4
}
```
### Constructor Nombrado
```dart
class Point {
double x;
double y;
Point(this.x, this.y);
// Constructor nombrado
Point.origin()
: x = 0,
y = 0;
Point.fromJson(Map json)
: x = json['x'] as double,
y = json['y'] as double;
}
void main() {
var p1 = Point.origin();
var p2 = Point.fromJson({'x': 5.0, 'y': 10.0});
print('${p1.x}, ${p1.y}'); // 0, 0
print('${p2.x}, ${p2.y}'); // 5, 10
}
```
### Constructor con Inicializadores
```dart
class Person {
String name;
final int birthYear;
Person(this.name, this.birthYear);
// Lista de inicializadores
Person.withAge(String name, int age)
: name = name,
birthYear = DateTime.now().year - age;
}
void main() {
var p1 = Person('Alice', 1990);
var p2 = Person.withAge('Bob', 25);
print('${p1.name} nacio ${p1.birthYear}'); // Alice nacio 1990
print('${p2.name} nacio ${p2.birthYear}'); // Bob nacio 1999
}
```
### Constructores de Redireccion
```dart
class Person {
String name;
int age;
// Constructor primario
Person(this.name, this.age);
// Redirige al primario
Person.guest() : this('Invitado', 0);
}
void main() {
var guest = Person.guest();
print('${guest.name}, ${guest.age}'); // Invitado, 0
}
```
### Constructor Constante
```dart
class ImmutablePoint {
final double x;
final double y;
const ImmutablePoint(this.x, this.y);
}
void main() {
var p1 = const ImmutablePoint(0, 0);
var p2 = const ImmutablePoint(0, 0);
print(identical(p1, p2)); // true (misma instancia)
}
```
## Constructores Factory
### Patron Singleton
```dart
class Database {
static final Database _instance = Database._internal();
factory Database() => _instance;
Database._internal();
void query(String sql) {
print('Ejecutando: $sql');
}
}
void main() {
var db1 = Database();
var db2 = Database();
print(identical(db1, db2)); // true (misma instancia)
}
```
### Desde Cache
```dart
class Cache {
static final Map _cache = {};
final String key;
factory Cache(String key) {
return _cache.putIfAbsent(key, () => Cache._internal(key));
}
Cache._internal(this.key);
}
void main() {
var c1 = Cache('user');
var c2 = Cache('user');
print(identical(c1, c2)); // true
}
```
## Miembros Estaticos
### Campos Estaticos
```dart
class Counter {
static int count = 0;
Counter() {
count++;
}
static void reset() {
count = 0;
}
}
void main() {
Counter();
Counter();
Counter();
print(Counter.count); // 3
Counter.reset();
print(Counter.count); // 0
}
```
### Metodos Estaticos
```dart
class MathUtils {
static int square(int x) => x * x;
static double circleArea(double radius) =>
3.14159 * radius * radius;
// Puede llamarse sin instancia
}
void main() {
print(MathUtils.square(5)); // 25
print(MathUtils.circleArea(2)); // 12.56636
}
```
## Getters y Setters
### Getters/Setters Implicitos
```dart
class Person {
String _name = ''; // Campo privado
// Getter implicito
String get name => _name;
// Setter implicito
set name(String value) => _name = value;
}
void main() {
var p = Person();
p.name = 'Alice'; // Llama al setter
print(p.name); // Llama al getter
}
```
### Propiedades Calculadas
```dart
class Rectangle {
double width;
double height;
Rectangle(this.width, this.height);
// Propiedad calculada
double get area => width * height;
double get perimeter => 2 * (width + height);
}
void main() {
var rect = Rectangle(5, 10);
print(rect.area); // 50
print(rect.perimeter); // 30
}
```
## Enums
### Enum Basico
```dart
enum Color { red, green, blue }
void main() {
var color = Color.red;
print(color); // Color.red
print(color.index); // 0
// Iterar
for (var c in Color.values) {
print(c);
}
}
```
### Enum con Valores
```dart
enum Status {
pending('P'),
active('A'),
completed('C');
final String code;
const Status(this.code);
}
void main() {
print(Status.active.code); // A
}
```
### Enum con Metodos
```dart
enum Operation {
add,
subtract,
multiply;
int apply(int a, int b) {
switch (this) {
case Operation.add:
return a + b;
case Operation.subtract:
return a - b;
case Operation.multiply:
return a * b;
}
}
}
void main() {
print(Operation.add.apply(5, 3)); // 8
print(Operation.multiply.apply(5, 3)); // 15
}
```
## Extensiones
### Agregar Metodos a Clases Existentes
```dart
extension StringExtension on String {
String capitalize() {
if (isEmpty) return this;
return '${this[0].toUpperCase()}${substring(1)}';
}
bool get isEmail => contains('@');
}
void main() {
print('hello'.capitalize()); // Hello
print('test@email.com'.isEmail); // true
}
```
## Modificadores de Clase (Dart 3)
### Clase Final
```dart
final class FinalClass {
// No puede ser extendida
}
// class Extended extends FinalClass {} // Error
```
### Clase Base
```dart
base class BaseClass {
void baseMethod() {}
}
// Debe implementar la clase base correctamente
base class Derived implements BaseClass {
void baseMethod() {}
}
```
### Clase Interfaz
```dart
interface class InterfaceClass {
void interfaceMethod() {}
}
// Puede implementar pero no extender
class ImplementsInterface implements InterfaceClass {
void interfaceMethod() {}
}
```
### Clase Sellada
```dart
sealed class Result {}
// Subclases definidas en el mismo archivo
class Success extends Result {}
class Failure extends Result {}
```
## Resumen
- Clases: `class Nombre { campos, constructores, metodos }`
- Constructores: por defecto, parametrizado, nombrado, factory
- `this.nombreCampo` para inicializacion de parametros
- `static` para miembros de nivel de clase
- Getters/setters para acceso controlado
- `enum` para conjunto fijo de valores
- `extension` agrega metodos a tipos existentes
- Modificadores de clase Dart 3: final, base, interface, sealed
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →