為什么需要繼承
我現在要有兩個類一個? 一個是小學生,一個是大學生
代碼
小學生
package b;
public class encapsulatio{public String name;public int age;public double score;public void setscore (double score) {this.score=score;}public void testing() {System.out.println("小學生"+name+"正在準備考小學數學");}public void showinfo() {System.out.println("pupil name"+name+"age"+age+"score"+score);}}
大學生
package b;public class graduate {public String name;public int age;public double score;public void setscore (double score) {this.score=score;}public void testing() {System.out.println("University student"+name+"正在準備考小學數學");}public void showinfo() {System.out.println("pupil name"+name+"age"+age+"score"+score);}
}
你會發現,這兩個類實現的方法沒什么不同,
我在主類中
package b;public class main_ {public static void main(String[] args) {encapsulatio e=new encapsulatio() ;e.name="jacl";e.setscore(10);e.showinfo();}
}
看到了有這個小學生的
那么大學生
encapsulatio e=new encapsulatio() ;e.name="jacl";e.setscore(10);e.showinfo();graduate a=new graduate() ;a.name="jacl";a.setscore(10);a.showinfo();
這樣就很麻煩了那么繼承就出馬了
繼承的細節問題
子類能夠繼承所有屬性和方法,但是私有屬性和方法不能在子類直接訪問,通過公共方法訪問
但可以間接訪問,私有屬性和方法不能直接在子類中。要通過公有方法訪問
我先創建了主類。主類中有公有和私有屬性和方法
package b;public class father_ {//father class//4attributepublic int n1=100;protected int n2=200;int n3=400;public father_() {//無參構造器System.out.println("base(....");}public void test100() {System.out.println("test100");}protected void test200() {System.out.println("test200");}void test300() {System.out.println("test300");}private void test400() {System.out.println("test400");}
}
然后我創建了子類,并在子類中繼承主類
package b;public class graduate extends father_ {public graduate() {// TODO Auto-generated constructor stubSystem.out.println("graduate");}private void sayok() {//子類方法//非私有的屬性和方法可以直接在子類訪問,但私有屬性和方法不能在子類直接訪問System.out.println(n1+"-------"+n2+"-------"+n3);test100();test200();test300();test400();}
}
在用私有方法時The method test400() from the type father_ is not visible
然后我們再創建一個調用的類,就把他命名為main類
package b;public class main_ {public static void main(String[] args) {graduate gra=new graduate();gra.sayok();}
}
這里我們調用了graduate.發現它繼承的主類中的私有屬性和方法都不能訪問到
然后我們用公有的在父類中添加。
//父類提供公共方法訪問public int getn3() {return n4;}public void callback400() {test400();}
間接調用私有變量和屬性
結果
base(....
graduate
100-------200-------400
test100
test200
test300
test400
分享一個快捷鍵同時選多個
如下圖所示,快捷鍵shift + alt + a 之后按鈕鼠標左鍵往下滑則可實現多行操作的功能,退出則再shift + alt + a 一次即可
ctrl+pagup切換tab
alt +esc在多個屏幕切換焦點