Java关键字super的使用
在java中派生类继承基类,如果想访问派生类和基类的方法,我们可以重写父类的方法,并且通过super调用父类的方法就可以实现访问父类的方法
代码实例
public class People {
public void eat(){
System.out.println(" People eat()");
}
}
public class man extends People{
@Override
public void eat() {
super.eat();
System.out.println(" man eat()");
}
}
public static void main(String[] args) throws Exception {
People man = new man();
man.eat();
}
日志打印
People eat()
man eat()
C++中virtual的使用
在C++中,如果派生类继承基类都有相同的方法,如果我们想执行派生类的方法,那么我们就需要在基类中用virtual关键字来修饰该方法,如果不用virtual关键字来修饰该方法,那么就会执行基类中的方法
代码实例
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Human {
private:
int a;
public:
virtual void eating(void) { cout<<"Human eating(void)"<<endl; }
virtual ~Human() { cout<<"~Human()"<<endl; }
};
class Englishman : public Human {
public:
void eating(void) { cout<<"Englishman eating(void) "<<endl; }
virtual ~Englishman() { cout<<"~Englishman()"<<endl; }
};
int main(int argc, char **argv)
{
Englishman e;
Human *h = &e;
h->eating();
return 0;
}
日志打印
Englishman eating(void)
~Englishman()
~Human()