Java oop9:老師類繼承自人類或聲明U盤類實現接口,使用多態(tài)數組打印其各自的方法,

/*1.聲明一個父類人類,子類老師類繼承自人類,子類學生類繼承自人類,使用多態(tài)數組打印其各自的方法
*/
package a;
public class Student {
public static void main(String[] args) {
person j = new xueSheng("張三");
person l = new xueSheng("李四");
person c = new laoShi("王五");
person[] ms = new person[3];
ms[0] = l;
ms[1] = j;
ms[2] = c;
for (int i = 0; i < ms.length; i++) {
if (ms[i] instanceof xueSheng) {
((xueSheng) ms[i]).zuoZuoYeY();}
else if (ms[i] instanceof laoShi) {
((laoShi) ms[i]).gouWuW();
}
}
}
}
?class person {
public String name;/* 抽象類中這個可以不要 */
public person(String name/* 抽象類中這個可以不要 */) {
super();// 抽象類中這個可以不要
this.name = name;// 抽象類中這個可以不要
}
}
class xueSheng extends person? {
// 調用父類的構造方 法
public xueSheng(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public void zuoZuoYeY() {
// TODO Auto-generated method stub
System.out.println(this.name + "做作業(yè)");
}
}
class laoShi extends person {
public laoShi(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public void gouWuW() {
// TODO Auto-generated method stub
System.out.println(this.name + "購物");
}
}
/*有時候代碼沒錯也會暫時報錯:*/

/*
2.聲明一個存儲數據的接口,聲明U盤類實現接口,
聲明硬盤類實現接口,聲明MP3類實現接口,使用多態(tài)數組打印其各自的功能*/
package a;
public class Student {
public static void main(String[] args) {
renWu j/*父類*/=new UPan/*子類*/ ("U盤"/*賦值*/);
((UPan)/*轉換*/j).gongNeng();
renWu c=new yingPan("硬盤");
((yingPan)c).gongNeng();
renWu m=new MP3("MP3");
((MP3)m).gongNeng();
}
}
interface chuCunShuJv{
void gongNeng();
}
abstract/*抽象*/class renWu/*父類*/{
public String name;/*設參數*/
public renWu(String name/*接收參數*/) {
super();/*extends繼承時會用的super*/
this.name = name;/*聲明這個類里的name 是接收到的name,有自己說得通的理解即可*/
}
}
class UPan/*子類*/extends/*繼承*/ renWu/*父類*/implements/*接口*/ chuCunShuJv{
public UPan (String string) {
super(string);
}
@Override
public void gongNeng() {
System.out.println(this.name+"有拷貝的功能");/*里面有System.out.println的一般是public void gongNeng()這類的構造方法*/
}
}
class yingPan/*子類*/extends/*繼承*/ renWu/*父類*/implements/*接口*/ chuCunShuJv{
public yingPan (String string) {
super(string);
}
@Override
public void gongNeng() {
System.out.println(this.name+"好玩");/*里面有System.out.println的一般是public void gongNeng()這類的構造方法*/
}
}
class MP3 extends renWu implements chuCunShuJv{
public MP3(String name) {
super(name);
}
@Override
public void gongNeng() {
System.out.println(this.name+"聽歌");
}
}
