第七章 复用代码 && 第八章 多态

来源:互联网 发布: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
原创粉丝点击