我们可以在Java接口中定义一个类吗?
是的,您可以在接口内定义一个类。通常,如果接口的方法使用此类,并且在其他地方不使用它,则将在接口内声明一个类。
示例
interface Library {void issueBook(Book b);
void retrieveBook(Book b);
public class Book {
int bookId;
String bookName;
int issueDate;
int returnDate;
}
}
public class Sample implements Library {
public void issueBook(Book b) {
System.out.println("Book Issued");
}
public void retrieveBook(Book b) {
System.out.println("Book Retrieved");
}
public static void main(String args[]) {
Sample obj = new Sample();
obj.issueBook(new Library.Book());
obj.retrieveBook(new Library.Book());
}
}
输出结果
Hello welcome to nhooo
如果我们需要提供接口的默认实现,我们将在接口内部定义一个类,如下所示:
示例
interface Library {void issueBook(Book b);
void retrieveBook(Book b);
public class Book implements Library {
int bookId;
String bookName;
int issueDate;
int returnDate;
public void issueBook(Book b) {
System.out.println("book issued");
}
public void retrieveBook(Book b) {
System.out.println("book retrieved");
}
}
}
public class Sample {
public void demo() {
System.out.println("Hello welcome to nhooo");
}
public static void main(String args[]) {
Sample obj = new Sample();
obj.demo();
}
}
以上是 我们可以在Java接口中定义一个类吗? 的全部内容, 来源链接: utcz.com/z/350306.html