- 继承就是子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方法,或子类从父类继承方法,使得子类具有父类相同的行为。
News.java
package com.LessonTwo.java.model;
public class News {
private String title;
private String content;
protected News(){}
//构造的自由和责任交给用户
public News(String title, String content){
this.title = title;
this.content = content;
}
public String getTitle(){
return title;
}
public String getContent(){
return content;
}
//控制如何显示
public String display(){
return title + "\n" + content;
}
}
FileNews.java
package com.LessonTwo.java.model;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class FileNews extends News {
//有参数构造函数
public FileNews(String title,String content){
super(title,content); //承继父类
}
//无参数构造函数
public FileNews(){
super();
}
//读方法
public void read(String url){
try {
BufferedReader reader = new BufferedReader(new FileReader(new File(url)));
} catch (java.io.IOException e) {
System.out.println("新闻读取出错");
}
}
@Override
//承继父类并重写
public String display(){
return super.display() + "\n" + "from FileNews 的子类";
}
}
网友评论