Java的多态
多态的含义
多态:就是同一个行为具有不同的表现形式或形态的能力。
多态存在的三个必要条件
- 继承
- 重写
- 向上转型
多态的实例(Java)
class One{
public void getValue(){
System.out.println("super类的getValue方法");
}
}
class Two extends One{
@Override
public void getValue(){
System.out.println("Two类的getValue方法");
}
}
class Three extends One{
@Override
public void getValue(){
System.out.println("Three类的getValue方法");
}
}
public class Test_1 {
public static void main(String[] args) {
One a = new One();
Two b = new Two();
Three c = new Three();
a.getValue();
a = b;
a.getValue();
a = c;
a.getValue();
}
}
run:
super类的getValue方法
Two类的getValue方法
Three类的getValue方法
虚函数
虚函数的存在就是为了实现多态。
C++里的虚函数
#include<iostream>
using namespace std;
class One{
public:
void getValue(){
cout<<"super类的函数"<<endl;
}
};
class Two : public One{
public:
void getValue(){
cout<<"子类的函数"<<endl;
}
};
int main(){
One *p;
One a;
Two b;
p = &a;
p->getValue();
p = &b;
p->getValue();
return 0;
}
/*输出结果为:
super类的函数
super类的函数
*/
//当在父类的方法名前添加上virtual关键字时,该方法就被声明为虚函数,当向上转型时,会调用子类中重写后的方法。
#include<iostream>
using namespace std;
class One{
public:
void virtual getValue(){
cout<<"super类的函数"<<endl;
}
};
class Two : public One{
public:
void getValue(){
cout<<"子类的函数"<<endl;
}
};
int main(){
One *p;
One a;
Two b;
p = &a;
p->getValue();
p = &b;
p->getValue();
return 0;
}
/*输出结果为:
super类的函数
子类的函数
*/
通过这个例子,可以看到虚函数的作用------实现多态。指向基类的指针在操作它的多态类对象时,会根据不同的类对象,调用其相应的函数,这个函数就是虚函数。
Java里所谓的“虚函数”
class One{
public void getValue(){
System.out.println("super类的getValue方法");
}
}
class Two extends One{
@Override
public void getValue(){
System.out.println("Two类的getValue方法");
}
}
class Three extends One{
@Override
public void getValue(){
System.out.println("Three类的getValue方法");
}
}
public class Test_1 {
public static void main(String[] args) {
One a = new One();
Two b = new Two();
Three c = new Three();
a.getValue();
a = b;
a.getValue();
a = c;
、 a.getValue();
}
}
在上面的代码中,我们同样定义了一个基类指针(在java中应该叫引用)去指向不同的对象,可以发现同样可以实现多态。也就是说,java的普通成员函数就是虚函数,原因很简单,它本身就实现虚函数实现的功能------多态。