Práctica: Máximo

Escriba una subrutina que calcule el máximo de los elementos de una lista. Aplíquela a listas de números, cadenas, números fraccionarios y números complejos.

Para sobrecargar los operadores de comparación deberá especificar que la clase Rational implementa la interface Comparable y proveer el método compareTo:

public class Rational implements Comparable {
   private int num;
   private int dem;

   Rational(int a, b) { 
      assert (b != 0);
      if (b < 0) {
        b = -b
        a = -a
      }
      int x = mcd(a, b);
      num = a/x;
      dem = b/x;
   }
   
   Rational(int a) { num = a; dem = 1 }
   ..................................

   int mcd(int a, b) {
      return (b == 0) ? a : mcd(b, a - (b * (int) Math.floor(a/b))); 
   }

   ..................................

   public int compareTo(Object obj) {
     obj.dem*this.num <=> obj.num*this.dem
   }

}
An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signatures and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions.

As interfaces are implicitly abstract, they cannot be directly instantiated except when instantiated by a class that implements the said interface. The class must implement all of the methods described in the interface, or be an abstract class.

Object references in Java may be specified to be of an interface type; in which case, they must either be null, or be bound to an object that implements the interface.

One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java (other than java.lang.Object, the root class of the Java type system) must have exactly one base class; multiple inheritance of classes is not allowed.

Furthermore, a Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.

Casiano Rodríguez León
2010-04-30