类的继承
来源:互联网 发布: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的类,把完整的代码写进去才行。运行结果如下
- c++类的继承:私有继承,公有继承,保护继承
- 类的继承 保护继承和私有继承
- C#类的继承-什么是继承
- 继承QVector----模板类的继承
- 类的一般继承与虚继承
- 继承:单继承、派生类成员的访问属性、多继承、菱形继承、虚继承,菱形虚拟继承
- java 类的继承
- 类的继承
- C#类的继承
- JavaScript类的继承
- C++ 类的继承
- 类的继承
- Java类的继承
- 类的继承
- 抽象类的继承
- 类的继承
- 类的继承用法
- 类的继承方式
- Javascript继承机制的设计思想
- USB-HDD,USB-ZIP,USB-HDD+,USB-ZIP+之间的关系
- 奇怪的排序
- JDBC的表与对象
- Javascript 面向对象编程(一):封装
- 类的继承
- MyEclipse的快捷使用(含关联源码和Doc的方式)
- 项目的一般流程
- Javascript面向对象编程(二):构造函数的继承
- Dropbox VS 华为网盘
- 2013 年规划
- Android中Bitmap和Drawable
- javascript闭包的作用域链引出的副作用
- Javascript面向对象编程(三):非构造函数的继承