封装:是指一种将类实现细节部分包装,隐藏起来的方法。只暴露使用的方法。
低耦合是暴露的信息较少,解耦相对简单。
继承:可以抽离公共部分,进行代码的简化。子类对父类进行拓展,拓展可以是新创建也可以是对原有的修改。
package com.company;
import java.io.*;
public class File {
private String file;
public File(String file) {
this.file = file;
}
public String readToString() throws IOException {
CharArrayWriter writer = new CharArrayWriter();
InputStreamReader reader =
new InputStreamReader(
new BufferedInputStream(
new FileInputStream(this.file)), "UTF-8");
char[] charArr = new char[512];
int readChars;
String ret;
try {
while ((readChars = reader.read(charArr)) != -1) {
writer.write(charArr, 0, readChars);
}
ret = writer.toString();
}finally {
reader.close();
writer.close();
}
return ret;
}
public void writeString(String content)throws IOException{
PrintWriter writer = new PrintWriter(this.file);
try {
writer.print(content);
}finally {
writer.close();
}
}
}
如上代码,主要暴露给用户使用的接口,不暴露内部具体的实现。
package com.company;
public class News {
protected String title; //拓展子类功能,使用protected
protected String content;
public News(String title,String content){
this.title = title;
this.content = content;
}
protected News () {
}
/* 阻止改动title
public void setTitle(String title) {
this.title = title;
}
*/
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
//控制显示
public String display(){
return title + "\n" + content;
}
}
package com.company;
import java.io.*;
import java.io.File;
public class FileNews extends News {
public FileNews(String title, String content) {
super(title, content);
}
public FileNews() {
}
public void read(String url) {
try {
BufferedReader reader = new BufferedReader(new FileReader(new File(url)));
title = reader.readLine(); //读取title
reader.readLine(); // 跳过空行
content = reader.readLine(); //读取content
} catch (java.io.IOException e) {
System.out.println("出错");
}
}
}
以上代码,子类继承父类,并可对功能进行了拓展。