image.png
封裝:是指一種將類實現(xiàn)細節(jié)部分包裝,隱藏起來的方法柜蜈。只暴露使用的方法仗谆。
低耦合是暴露的信息較少,解耦相對簡單淑履。
image.png
繼承:可以抽離公共部分隶垮,進行代碼的簡化。子類對父類進行拓展秘噪,拓展可以是新創(chuàng)建也可以是對原有的修改狸吞。
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();
}
}
}
如上代碼,主要暴露給用戶使用的接口指煎,不暴露內(nèi)部具體的實現(xiàn)蹋偏。
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("出錯");
}
}
}
以上代碼至壤,子類繼承父類暖侨,并可對功能進行了拓展。