c++和java中父类指向子类的比较

来源:互联网 发布:电话号码扫描录入软件 编辑:程序博客网 时间:2024/06/08 13:27

1.java

一般使用父类变量指向子类实例,该父类变量可显性化子类方法,不能调用父类不存在的变量和方法。

class Animal {    Animal(){System.out.println("this is animal");}    public void move(){    System.out.println("animal move");    } }class Dog extends Animal{    public int age;    Dog(){System.out.println("this is a dog");}    public void move(){    age = 10;    System.out.println("dog's age is 10");    }    public void bark(){    System.out.println("dogs can bark");    }}public class Test {      public static void main(String args[]){    Animal a = new Animal(); // 父类构造函数执行一次    Animal b = new Dog();     //父类指向子对象,父类构造一次,子类构造一次,b调用子类方法(但非全部)    Dog c = new Dog();      // 父类构造一次,子类构造一次         a.move();                // 执行父类的方法    b.move();                // *执行子类的方法//*多态 // b.bark();//异常    c.bark();       }       }

java中多态的条件:1 、继承 2、重写   3、父类引用指向子类对象

2. c++

基类指针指向派生类对象,该指针只能调用基类函数。

#include <iostream> using namespace std; class father{  public:  father():age(54){cout<<"build father,and father's age is :"<<age<<"\n";}  ~father(){cout<<"dispose father\n";}  void jump()const {cout<<"father jump low\n";}  void run()const{cout<<"father run slowly\n";}  protected:  int age;};class son:public father{  public:  son(){cout<<"build son\n";}  ~son(){cout<<"dispose son\n";}  void math(){cout<<"son's math is good\n";}  void jump()const {cout<<"son jumps high\n";}  void run()const{cout<<"son run fast\n";}};void main() { father *pfather=new son;//在堆中创建一个派生类对象,并赋给基类指针。pfather->jump();        //用该指针访问父类中的jump函数pfather->run();         //用该指针访问父类中的run函数//pfather->math();      //errordelete pfather;         //删除基类指针指向的派生类的对象system("pause");                }

若改成son *p=new son;p->run();则调用子类成员函数。

原创粉丝点击