VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • Java学习笔记(十一)面向对象---多态(2)


1 2
 
 

5|3多态中静态成员函数(变量)的特点

无论编译还是运行,都参考左边。 静态类型,静态绑定。 非静态类型,动态绑定。


class Fu { static void method1() { System.out.println("Fu_Method_1"); } } class Zi extends Fu { static void method1() { System.out.println("Zi_Method_1"); } } public class Demo5 { public static void main(String[] args) { Fu f = new Zi(); f.method1(); Zi z = new Zi(); z.method1(); } }
 
 

运行结果:


Fu_Method_1 Zi_Method_1
 
 

6|0多态-转型


abstract class Animal { public abstract void eat(); } class Cat extends Animal { @Override public void eat() { System.out.println("eat fish"); } public void CatchMouse() { System.out.println("CatchMouse"); } } class Dog extends Animal { @Override public void eat() { System.out.println("eat bone"); } public void GuardHouse() { System.out.println("GuardHouse"); } } class Monkey extends Animal { @Override public void eat() { System.out.println("eat banana"); } public void PlayBall() { System.out.println("Play Ball"); } } public class Demo1 { public static void main(String[] args) { function(new Cat()); function(new Dog()); function(new Monkey()); } public static void function(Animal a) { a.eat(); if (a instanceof Cat) { //instanceof关键字用于判断所属类型 Cat c = (Cat)a; //向下转型 c.CatchMouse(); } else if (a instanceof Dog) { Dog d = (Dog)a; //向下转型 d.GuardHouse(); } else { Monkey m = (Monkey)a;//向下转型 m.PlayBall(); } } }
 
 

运行结果:


eat fish CatchMouse eat bone GuardHouse eat banana Play Ball
 
 

7|0多态的应用

以电脑主板为例的示例 分析电脑主板要考虑到拓展性,使用了pci接口,板卡(声卡,网卡等)和主板都遵循pci接口。


interface Pci { public void open(); public void close(); } class MainBoard { public void run() { System.out.println("Main Board run"); } public void usePci(Pci p){ //接口类型指向自己的子类对象 if(p != null){ //加入判断防止空指针 p.open(); p.close(); } } } class Netcard implements Pci { @Override public void open() { System.out.println("Netcard open"); } @Override public void close() { System.out.println("Netcard close"); } } class Soundcard implements Pci { @Override public void open() { System.out.println("Soundcard open"); } @Override public void close() { System.out.println("Soundcard close"); } } public class Demo6 { public static void main(String[] args) { MainBoard mb = new MainBoard(); mb.run(); mb.usePci(null); mb.usePci(new Netcard()); mb.usePci(new Soundcard()); } }
 
 

运行结果


Main Board run Netcard open Netcard close Soundcard open Soundcard close
 
 

__EOF__

本文作者Liyuxin 本文链接:https://www.cnblogs.com/liyuxin2/p/12313781.html


相关教程