第七章 复用代码 && 第八章 多态
来源:互联网 发布:red hat linux 9 编辑:程序博客网 时间:2024/05/17 06:28
1 对象组合
在一个对象中,定义对另外对象的引用;
2.继承
super关键字
2.1初始化基类
class component1{component1(int i){System.out.println("component1 "+i);}}class component2{component2(int i){System.out.println("component1 "+i);}}class Root{component1 comp1;component2 comp2;Root(int i,int j){comp1=new component1(i);comp2=new component2(j);System.out.println("root");}}public class Stem extends Root {Stem() {super(1, 2);// TODO Auto-generated constructor stub}Stem(int i,int j) {super(i, j);// TODO Auto-generated constructor stub}public static void main(String[] args){System.out.println("start");new Stem();new Stem(3,4);}}
实际上,生产过程中我盟更多的是使用组合,而非继承,一个清晰的判断方法是考虑新类是否需要向上转型,如果需要,则继承;否则组合;(reason)?
final关键字:表示这是无法改变的;通常用于数据、方法、类;byw,this,super,static;
多态
java中除了static 、final方法外,其它所有的方法都是后期绑定;为什么需要将某些方法声明为final呢?这样,可以有效的“关闭”动态绑定,或者说告诉编译器不需要进行动态绑定;
package sun.polyphism.shape;public class shape {public void draw(){//System.out.println("shape");}}
package sun.polyphism.shape;public class circle extends shape{public void draw(){System.out.println("circle draw");}}
package sun.polyphism.shape;public class triangle extends shape {public void draw(){System.out.println("triangle draw");}
<span style="font-family: Arial, Helvetica, sans-serif;">}</span>
import java.util.Random;public class RandomShapeFac {private Random rand=new Random(47);public shape next(){/*if(rand.nextInt(2)==0)return new circle();elseif(rand.nextInt(2)==1)return new triangle();return new shape();*/switch(rand.nextInt(2)){default:{System.out.println("default");}case 0:{System.out.println("case 0");return new circle();}case 1:{System.out.println("case 1");return new triangle();}}}}
package sun.polyphism.shape;public class shapes {/** * @param args */public static RandomShapeFac gen=new RandomShapeFac();public static void main(String[] args) {// TODO Auto-generated method stubshape[] s=new shape[9];for(int i=0;i<s.length;i++){gen.next().draw();}//for(shape shp:s)//shp.draw();}}
0 0
- 第七章 复用代码 && 第八章 多态
- 第七章第八章总结
- 《第一行代码》读书笔记(第七章,第八章,第九章)
- 第七章:函数、第八章:数组
- python 核心编程 第七章 第八题
- 第七章代码
- 第七章代码2
- Thinking in Java 第七章 多态 第八章:接口与内部类 第九章:异常处理
- 第七章+第八章 参数传递和判断
- (第七章略)第八章 路由选择
- 第八章 TriGridDemo重点代码
- 第八章 MeshDemo核心代码
- 第七周 项目三:第八章知识点思维导图
- 生成数据 (代码大全 第八章 )
- 算法导论 python代码 第八章
- 第一行代码 第八章源码漏洞
- 第二行代码第八章笔记
- 读《编译原理》第八章,代码生成
- 网站的所有页面底部多出来了一个js代码
- Hibernate Projections(投影、统计、不重复结果)
- oracle的一些操作
- php学习笔记(十四)变量
- 分布式系统的事务处理
- 第七章 复用代码 && 第八章 多态
- 你所不知道的几个经济学真相
- UIScrollView的属性总结
- XX和OO(南阳oj1159)
- Android之dumpsys
- MySQL建表的几个注意事项
- replica nfl jerseys
- 小白学opengl之显示回调函数与reshape回调函数
- amfphp资料