The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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. Only default and static methods have implementations.
Question 3: Fix the interface in Question 2.
Answer 3:
public interface SomethingIsWrong { void aMethod(int aValue); }
Alternatively, you can define aMethod
as a default method:
public interface SomethingIsWrong { default void aMethod(int aValue) { System.out.println("Hi Mom"); } }
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.
Exercise 1: Write a class that implements the CharSequence
interface found in the java.lang
package. Your implementation should return the string backwards. 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
.