Virtual Function in Java and Cpp

in Cpp

when the reference of parent class points to child class object,the reference can not directly invoke child-class-specific methods;To address the limitation,virtual function were intorduced;By prefixing parent-class-method with vitrual keyword,these methods become overridable,allowing child class to override them and enable dynamic dispatch based on the object’s actual type at runtime;

A prime example in cpp

#include <iostream>
using namespace std;

class Animal {
public:
    virtual void eat() {  
        cout << "animal eating" << endl;
    }
};  

class Dog : public Animal {  
public:
    void eat() override {  //override keyword is optional,adding "override" is explicit,and the opposite is implicit;
        cout << "dog eating bone" << endl;
    }
};  // 类定义结束需要分号

int main() {
    Animal* dog = new Dog();  
    dog->eat();               //dog eating bone    
    delete dog;               // 释放内存(实际开发中建议用智能指针)
    return 0;
}
  • Unlike c++ ,java achieve the same effect in polymorphism obly by using the “@override” keyword;

  • A prime example in Java

public class test{
public static class Animal{
		public void eat(){
				System.out.println("animal is eatind");
			}
	}
	
public static class Dog extends Animal{
		@Override
		public void eat(){
				System.out.println("Dog is eating");
			}
	}
	
public static void main(String args[]){
		Animal dog=new Dog();
		dog.eat();          //Dog is eating
	}
	}

Weather in java or c++,there are must no limitate keywords such as "private","final","protected" in front of virtual funtion

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值