Estoy trabajando en una tarea para mi en la clase de programación que implica la implementación de interfaces. El problema aquí es que realmente me cuesta trabajo no entender interfaces o para qué se utilizan (el profesor no fue muy bueno para explicarlo).Java - Implementing Interfaces
La tarea consistía en crear una superclase "Vehículo", y tres subclases, algo así como "Camión" o "Jeep" que tendrían cada uno un par de características propias. La clase "Vehículo" debe implementar la interfaz comparable, que creo que he descubierto (tengo el método compareTo()
escrito comparando el número de puertas en los vehículos), y otra clase también debe implementar la clase "Híbrida" (no tengo idea de lo que esto significa). Luego tenemos que implementar los métodos toString()
, equals(Object o)
y compareTo(Object o)
.
Creo que tengo el compareTo()
hacia abajo, pero con el equals()
no tengo ni idea. Lo último que tenemos que hacer es escribir un Main para probar, esto implica hacer una matriz de objetos del Vehículo, imprimirlos, clasificarlos y luego volver a imprimirlos. También debe iterar a través de la matriz e imprimir la prima de precio para los híbridos, y utilizar el método equals(Object o)
para comparar 2 vehículos.
Este es el código para mi superclase "vehículo"
package vehicle;
abstract public class Vehicle implements Comparable {
private String color;
private int numberOfDoors;
// Constructor
/**
* Creates a vehicle with a color and number of doors
* @param aColor The color of the vehicle
* @param aNumberOfDoors The number of doors
*/
public Vehicle(String aColor, int aNumberOfDoors) {
this.color = aColor;
this.numberOfDoors = aNumberOfDoors;
}
// Getters
/**
* Gets the color of the vehicle
* @return The color of the vehicle
*/
public String getColor() {return(this.color);}
/**
* Gets the number of doors the vehicle has
* @return The number of doors the vehicle has
*/
public int getNumberOfDoors() {return(this.numberOfDoors);}
// Setters
/**
* Sets the color of the vehicle
* @param colorSet The color of the vehicle
*/
public void setColor(String colorSet) {this.color = colorSet;}
/**
* Sets the number of doors for the vehicle
* @param numberOfDoorsSet The number of doors to be set to the vehicle
*/
public void setNumberOfDoors(int numberOfDoorsSet) {this.numberOfDoors = numberOfDoorsSet;}
@Override
public int compareTo(Object o) {
if (o instanceof Vehicle) {
Vehicle v = (Vehicle)o;
return this.numberOfDoors - v.getNumberOfDoors();
}
else {
return 0;
}
}
/**
* Returns a short string describing the vehicle
* @return a description of the vehicle
*/
@Override
public String toString() {
String answer = "The car's color is "+this.color
+". The number of doors is"+this.numberOfDoors;
return answer;
}
}
Y también voy a publicar uno de mis subclases
package vehicle;
abstract public class Convertible extends Vehicle {
private int topSpeed;
// Constructor
/**
* Creates a convertible with a color, number of doors, and top speed
* @param aColor The color of the convertible
* @param aNumberOfDoors The number of doors of the convertible
* @param aTopSpeed The top speed of the convertible
*/
public Convertible (String aColor, int aNumberOfDoors, int aTopSpeed) {
super(aColor, aNumberOfDoors);
this.topSpeed = aTopSpeed;
}
// Getters
/**
* Gets the top speed of the convertible
* @return The top speed of the convertible
*/
public int getTopSpeed() {return(this.topSpeed);}
// Setters
/**
* Sets the top speed of the convertible
* @param topSpeedSet The top speed to set to the convertible
*/
public void setTopSpeed(int topSpeedSet) {this.topSpeed = topSpeedSet;}
/**
* Returns a short description of the convertible
* @return a short description of the convertible
*/
@Override
public String toString() {
String answer = "The car's color is "+super.getColor()
+", the number of doors is "+super.getNumberOfDoors()
+", and the top speed is "+this.topSpeed+" mph.";
return answer;
}
}
Definitivamente no estoy pidiendo a nadie a hacer el trabajo para mí, pero si alguien pudiera arrojar algo más de luz sobre cómo funcionan las interfaces y qué es lo que esta tarea en realidad está pidiendo, sería grandioso.
Toda la ayuda es muy apreciada
¡Gracias!
Una interfaz es básicamente un contrato para una clase. Dice que si quieres llamarte "Comparable" necesitas implementar estos métodos que forman un "Comparable". –
Una interfaz es solo una forma de obligar a las clases a verse y comportarse de una manera estandarizada. Cuando una interfaz define un método, cada clase que implementa esa interfaz DEBE anular ese método, lo que garantiza que esa clase tendrá su propia versión de ese método. – Hassan
espero que su profesor no lea esta pregunta. :) – Dhananjay