类的继承

来源:互联网 发布:windows官方下载地址 编辑:程序博客网 时间:2024/06/08 08:31

技术要点

1.继承父类

通过继承,可以获得父类中的所有方法,可以扩展父类,还可以重新书写父类。继承使用关键字extends表示

2.this和super

在java中有两个特殊的变量:this和super。this用来表示类本身,super用来表示父类的。在类的继承中,很有可能父类中的变量子类中叶存在,如何告诉虚拟机要使用哪个变量,这就要用this来指明本类中的变量,super指明父类中的变量

实现步骤

1.先写父类tree

 

class tree{

    publicvoid root(){

       String sSite="土壤中";

       String sFunction="吸收养分";

       System.out.println("位置:"+sSite);

       System.out.println("功能:"+sFunction);

    }

    publicvoid bolo(){

       String sSite="地面";

       String sFunction="传递养分";

       System.out.println("位置:"+sSite);

       System.out.println("功能:"+sFunction);

    }

    publicvoid branch(){

       String sSite="树干上";

       String sFunction="传递养分";

       System.out.println("位置:"+sSite);

       System.out.println("功能:"+sFunction);

    }

    publicvoid leaf(){

       String sSite="树梢";

       String sFunction="光合作用";

       String sColor="绿色";

       System.out.println("位置:"+sSite);

       System.out.println("功能:"+sFunction);

       System.out.println("颜色:"+sColor);

    }

    publicvoidprint(ObjectoPara){System.out.println(oPara);}

    publicstaticvoid main(String[] ags){

       tree t=new tree();

       t.print("描述一棵树:");

       t.print("树根:");

       t.root();

       t.print("树干:");

       t.bolo();

       t.print("树干:");

       t.branch();

       t.print("树叶:");

       t.leaf();

    }

}

 tree类中定义了一个树的基本信息,像root,bolo,branch,和leaf,每一部分也都有相应的方法描述,这些方法构成了一个框架,结果如下

2.编写子类osier

class osier extends tree{
 public void leaf(){
  super.leaf();
  String sShape="长形";
  super.print("形状:"+sShape);
 }
 public void flower(){print("哈哈,柳树没有花!!");}
 public static void main(String ags[]){
  osier o=new osier();
  o.print("柳树树根:");
  o.root();
  o.print("柳树树干:");
  o.bolo();
  o.print("柳树树枝:");
  o.branch();
  o.print("柳树树叶:");
  o.leaf();
  o.print("柳树花:");
  o.flower();
 }
}
子类柳树继承tree类,获得了tree类中的所有方法。同时,super.leaf()语句获取父类对叶子的描述,有扩展了柳树的形状描述。方法flower()在父类中没有,在osier中叶添加了描述。

要注意的是,在运行结果是,如果用的是eclipse编译的,子类不能单独运行,必须重新建一个osier的类,把完整的代码写进去才行。运行结果如下

 

原创粉丝点击