十分鐘看完面向對象
前引:在java面向對象的學習中真的是難道無數人,本人也是常常被次困擾,面向對象主要在於對對象的理解,下面我們來對此進行講解。
面向對象特征:封裝,繼承,多態,抽象
封裝:封裝:什麽是封裝?大白話,你在網上買了一個蘋果筆記本電腦,你不用在意他的硬件,他怎麽生產的,他怎麽郵寄到你這的,
要在意的是,它能幹什麽?他可以打代碼,可以裝B,你只需要他能實現什麽功能,封裝到一個方法裏,到時候後你再去調用,就像上課老
師說的,狗能叫,魚能遊泳是一個意思。(不用在意他別的屬性細節)
public class Student {
public static void main(String[] args) {
Behaviour behaviour = new Behaviour("老王", "男", "Apple筆記本電腦");
behaviour.buy();
}
}
class Behaviour {
private String name;
private String sax;
private String computer;
public Behaviour(String string, String string2, String string3) {
super();
this.name = string;
this.sax = string2;
this.computer = string3;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSax() {
return sax;
}
public void setSax(String sax) {
this.sax = sax;
}
public String getComputer() {
return computer;
}
public void setComputer(String computer) {
this.computer = computer;
}
@Override
public String toString() {
return "behaviour [name=" + name + ", sax=" + sax + ", computer=" + computer + "]";
}
public void buy() {
System.out.println(this.toString());
}
}
繼承:們常說,你看老王的兒子和他爸一樣有力氣,WBQ的兒子一點不像他(沒有繼承他)前者就是完美的繼承,繼承了父親的良好基因,
在上課中老師常說的是,小狗繼承了老狗,老狗會叫,小狗也會叫,這就是繼承。
public class ex {
public static void main(String[] args) {
Father father = new Father(1000000, "北京二環別墅房1102");
father.say();
San san = new San(1000000, "北京二環別墅房1102" + "(這裏面是繼承過來)");
san.say();
}
}
class Father {
private int money;
private String house;
public Father(int money, String house) {
super();// 讓它成為父類,讓別的類繼承
this.money = money;
this.house = house;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public String getHouse() {
return house;
}
public void setHouse(String house) {
this.house = house;
}
public void say() {
System.out.println("我有" + this.money + "塊錢" + "並且" + this.house + "是我的房子");
}
}
class San extends Father {
public San(int money, String house) {// 自動調用父類的構造方法
super(money, house);
}
}
多態:
(難點)什麽是多態 ?舉個例子,高三的同學準備迎接高考,正好下一節課是體育課,你們的老師說,下節體育課停了,上我的英語,
(現在一個班的同學每個同學都是一個類)而每個同學對老師說的話做出的反應不同,想考清華北大的同學高興的手舞足蹈,而不想
學習的學生就不高興了,而這只是表示了兩大類,而其實是每個同學對此做出的反應都不一樣,就是每個類做出的反應都不同,這就
是多態。
import java.util.Arrays;
class zong {
public int ix;
public zong(int ix) {
this.ix = ix;
}
public void show() {
System.out.println(this.ix);
}
public void means1() {
System.out.println("means1");
means2();
}
public void means2() {
System.out.println("means2");
}
}
class JNC extends zong {
public JNC(int ix) {
super(ix);
}
public int iy;
public void means1(String a) {
System.out.println("FNC的means1.....");
means2();
}
public void means2() {
System.out.println("means2");
}
}
public class 多態 {
public static void main(String[] args) {
zong w = new zong(0);
w.means1();
JNC jnc = new JNC(0);
jnc.means1("as");
zong q = new JNC(5);
q.show();
}
}
十分鐘看完面向對象