62,614
社区成员
发帖
与我相关
我的任务
分享
// Interface
public interface InfoCommunication {
public Info sending();
public void receiving(Info info);
}
// Entrance
public class Test {
public static void main(String[] args) {
InfoCommunication frame = new MyFrame();
InfoCommunication data = new InfoData();
frame.receiving(data.sending());
}
}
// The class to show the data which is grabbed from Internet
public class MyFrame /*extends JFrame*/implements InfoCommunication{
Info info ;
public MyFrame() {
info = new Info();
}
@Override
public Info sending() {
//none
return null;
}
@Override
public void receiving(Info info) {
this.info = info;
}
}
// The class which aims to grab data
public class InfoData implements InfoCommunication {
Info info;
InfoData(){
info = new Info();
this.grabInfo();
}
private void grabInfo(){
//garb information from Internet, assuming that:
//author: Tom
//title: Passage title
//wordsCount: 1000
info.setAuthor("Tom");
info.setTitle("Passage title");
info.setWordsCount("1000");
}
@Override
public Info sending() {
return this.info;
}
@Override
public void receiving(Info info) {
//None
}
}
package test7;
public class MianXiangJieKou
{
public static void main(String[] args)
{
Book b1 = new Novel();
Book b2 = new Magazine();
Mather mather = new Mather();
mather.read(b1);
mather.read(b2);
}
}
interface Book
{
public void read();
}
class Novel implements Book
{
@Override
public void read()
{
System.out.println("读小说内容");
}
}
class Magazine implements Book
{
@Override
public void read()
{
System.out.println("读杂志内容");
}
}
class Mather
{
//mather能读书,不论是小说或者杂志。只要这本读物实现了Book都能被mather读。
//这就是面向接口的好处。
public void read(Book b)
{
b.read();
}
}
接口, 你可以看做是电脑的USB接口。定义了某个功能的名字, 然后具体的那个插件,只要插上去就可以实现相应的功能。
public class Info {
String title = "non-init";
String author = "non-init";
String wordsCount = "non-init";
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getWordsCount() {
return wordsCount;
}
public void setWordsCount(String wordsCount) {
this.wordsCount = wordsCount;
}
}