b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

java中多态举例_oop 多态_封装继承多态(2)

电脑杂谈  发布时间:2017-01-14 14:15:36  来源:网络整理

System.out.println("Woodwind4.play()");

}

public String what(){return"Woodwind4";}

}

public class Musi{

//Doesn't care about type,so new types

//added to the system still work right:

Static void tune(Instrument4i){

//...

i.play();

}

static void tuneAll(Instrument4[]e){

for(int i=0;itune(e[i]);

}

public static void main(String[] args){

Instrument4[] orchestra = newInstrument4[5];

int i = 0;

//Upcasting during addition to the array:

orchestra[i++]=new Wind4();

orchestra[i++]=new Percussion4();

orchestra[i++]=new Stringed4();

orchestra[i++]=new Brass4();

orchestra[i++]=new Woodwind4();

tuneAll(orchestra);

}

}///:~

(2)多态的重要性

为什么要说“语言不支持多态,就不能称之为面向对象的”。

传统的多态实际上就是由虚函数(Virtual Function)利用虚表(Virtual Table)实现的,自然是离不开继承,换句话说多态实际上覆盖了继承。正是由于继承与多态的紧密联系,使得我们很容易张冠李戴,那么如何区别呢?

举个常用的例子:

Abstract Class Sharp implement IHaveSide {

public bool isSharp(){

return true;

}

public abstract int getSides();

}

Class Triangle extends Sharp {

public override int getSides() {

return 3;

}

}

Class Rectangle extends Sharp {

pubilc override int getSides() {

return 4;

}

}

那么这种类的关系叫做继承,下面这种使用方式也是继承所带来的:

Triangel tri = new Triangle();

println("Triangle is a type of sharp? " + tri.isSharp());

而这种方式则是多态:

Sharp sharp = new Rectangle();

println("My sharp has " + sharp.getSides() + " sides.");

这两者区别在哪?很显然,继承是子类使用父类的方法,而多态则是父类使用子类的方法。其技术上的区别是绑定时期,后期绑定一定是多态(后面将要谈到什么是绑定)。

现代软件大量的使用框架、模式(非特指Deisgn Pattern),也就是将软件开发的一些共性进行抽象,提出普遍适用的软件结构。无论是框架还是模式,他们都有一些明显的共同点 — 使用xml配置对象,大量使用接口采用所谓面向接口的方法。


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-26262-2.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...