Answers to Questions and Exercises: Interfaces (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)
Trail: Learning the Java Language
Lesson: Interfaces and Inheritance
Home Page > Learning the Java Language > Interfaces and Inheritance
Answers to Questions and Exercises: Interfaces

Questions

Question 1: What methods would a class that implements the java.lang.CharSequence interface have to implement?
Answer 1: charAt, length, subSequence, and toString.

Question 2: What is wrong with the following interface?

public interface SomethingIsWrong {
    void aMethod(int aValue) {
        System.out.println("Hi Mom");
    }
}
Answer 2: It has a method implementation in it. It should just have a declaration.

Question 3: Fix the interface in Question 2.
Answer 3:

public interface SomethingIsWrong {
    void aMethod(int aValue);
}

Question 4: Is the following interface valid?

public interface Marker {
}
Answer 4: Yes. Methods are not required. Empty interfaces can be used as types and to mark classes without requiring any particular method implementations. For an example of a useful empty interface, see java.io.Serializable.

Exercises

Exercise 1: Write a class that implements the CharSequence interface found in the java.lang package. Select one of the sentences from this book to use as the data. Write a small main method to test your class; make sure to call all four methods.
Answer 1: See CharSequenceDemo.java

Exercise 2: Suppose that you have written a time server, which periodically notifies its clients of the current date and time. Write an interface that the server could use to enforce a particular protocol on its clients.
Answer 2: See TimeClient.java

Previous page: Questions and Exercises: Interfaces

  ATENCIÓN: La traducción de esta documentación es un esfuerzo personal y voluntario. NO es un documento oficial del propietario de la tecnología Java, Oracle, ni está patrocinado por esta empresa.

Los documentos originales y actualizados (en inglés) están disponibles en: http://docs.oracle.com/javase/tutorial/. La versión disponible en este sitio es la publicada en Marzo de 2008 (más información en: "What's new and What's Old? The History of the Tutorial").

Dirige cualquier comentario, petición, felicitación, etc. a tutorialesjava@codexion.com.

Si quieres ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesitas que se traduzca algún capítulo en concreto puedes invitarme a un café: