Ejercicio varias clases

Vamos a crear una clase Coche con las siguientes propiedades (todas privadas):

Marca
Modelo
Color
Velocidad

Las tres primeras las pasamos en el constructor, la velocidad la ponemos a 0.

Creamos setters y getters para todas las propiedades menos para la velocidad, para esta última sólo ponemos un getter. Comprobamos en todos los setters que el valor no esté vacío, en caso contrario lanzamos una excepción.

Vamos a crear un método acelerar y otro frenar. El primero aumenta la velocidad en 10 y el segundo la disminuye. El coche no puede tener velocidad negativa ni mayor de 140.

Crearemos el método toString que nos muestra la marca, el modelo y el color separados por espacio.

Vamos a crear la clase Carrera que tendrá las siguientes propiedades:

Nombre
Circuito
Coches

En el constructor pedimos las dos primeras, la tercera es un array vacío. Ponemos setters y getters en las dos primeras.

Crearemos un método addCoche al que le pasamos un objeto coche y se añade al array. Crearemos un método quitarCoche al que le pasamos un objeto coche y si hay un objeto de esa marca, modelo y color lo quitamos.

Primera versión:

class Coche {

    private $marca;
    private $modelo;
    private $color;
    private $velocidad=0;

    function __construct($marca, $modelo, $color) {
        $this->setColor($color);
        $this->setMarca($marca);
        $this->setModelo($modelo);
    }

    function acelerar() {
        $this->velocidad += 10;
        if ($this->velocidad > 140) {
            $this->velocidad = 140;
        }
    }

    function frenar() {
        $this->velocidad -= 10;
        if ($this->velocidad < 0) {
            $this->velocidad = 0;
        }
    }

    function __toString() {
        return $this->getMarca() . " " . $this->getModelo() . " " . $this->getColor();
    }

    function getMarca() {
        return $this->marca;
    }

    function getModelo() {
        return $this->modelo;
    }

    function getColor() {
        return $this->color;
    }

    function getVelocidad() {
        return $this->velocidad;
    }

    function setMarca($marca) {
        if (empty($marca)) {
            throw new Exception("La marca no puede estar vacía");
        }
        $this->marca = $marca;
    }

    function setModelo($modelo) {
        if (empty($modelo)) {
            throw new Exception("El modelo no puede estar vacía");
        }
        $this->modelo = $modelo;
    }

    function setColor($color) {
        if (empty($modelo)) {
            throw new Exception("El color no puede estar vacía");
        }
        $this->color = $color;
    }


}

Otra versión:

class Coche {

    private $marca;
    private $modelo;
    private $color;
    private $velocidad;

    function __construct($marca, $modelo, $color) {
        $this->setColor($color);
        $this->setMarca($marca);
        $this->setModelo($modelo);
        $this->setVelocidad(0);
    }

    function acelerar() {
        $this->setVelocidad($this->getVelocidad() + 10);
    }

    function frenar() {
        $this->setVelocidad($this->getVelocidad() - 10);
    }

    function __toString() {
        return $this->getMarca() . " " . $this->getModelo() . " " . $this->getColor();
    }

    function getMarca() {
        return $this->marca;
    }

    function getModelo() {
        return $this->modelo;
    }

    function getColor() {
        return $this->color;
    }

    function getVelocidad() {
        return $this->velocidad;
    }

    function setMarca($marca) {
        $this->checkParam($marca, "La marca no puede estar vacío");
        $this->marca = $marca;
    }

    function setModelo($modelo) {
        $this->checkParam($modelo, "El modelo no puede estar vacío");
        $this->modelo = $modelo;
    }

    function setColor($color) {
        $this->checkParam($color, "El color no puede estar vacío");
        $this->color = $color;
    }

    private function checkParam($param, $message) {
        if (empty($param)) {
            throw new Exception($message);
        }
    }

    private function setVelocidad($velocidad) {
        $this->velocidad = $velocidad;
        if ($this->velocidad > 140) {
            $this->velocidad = 140;
        }
        if ($this->velocidad < 0) {
            $this->velocidad = 0;
        }
    }

}

Carrera:

class Carrera {

    private $nombre;
    private $circuito;
    private $coches = [];

    function __construct($nombre, $circuito) {
        $this->setCircuito($circuito);
        $this->setNombre($nombre);
    }

    function addCoche(Coche $coche) {
        $this->coches[] = $coche;
    }

    function quitarCoche(Coche $coche) {
        for ($i = 0; $i < count($this->coches); $i++) {
            $c = $this->coches[$i];
            if ($c->getModelo() == $coche->getModelo() &&
                    $c->getMarca() == $coche->getMarca() &&
                    $c->getColor() == $coche->getColor()) {
                array_slice($this->coches, $i, 1);
            }
        }
    }

    function getNombre() {
        return $this->nombre;
    }

    function getCircuito() {
        return $this->circuito;
    }

    function setNombre($nombre) {
        $this->nombre = $nombre;
    }

    function setCircuito($circuito) {
        $this->circuito = $circuito;
    }

}

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos