C++开发者眼中的Java关键字abstract
C++中实现虚函数多态,需要使用virtual关键字,例如:
#include <iostream>
class Base {
public:
virtual void foo() { std::cout << "Base::foo()" << std::endl; }
};
class Derived : public Base {
public:
void foo() { std::cout << "Derived::foo()" << std::endl; }
};
int main(int argc, char** argv) {
Base* pb = new Derived();
pb->foo(); // call Derived::foo()
}
Java中没有virtual关键字,默认情况下,所有非静态函数都是虚函数,例如:
class Base {
public void foo() { System.out.println("Base::foo()"); }
}
class Derived extends Base {
public void foo() { System.out.println("Derived::foo()"); }
}
class Main {
public static void main(String argv[]) {
Base pb = new Derived();
pb.foo(); // call Derived::foo()
}
}
而C++中没有接口的概念,要实现类似Java中的接口,需要将虚函数声明为纯虚函数(在虚函数后面添加“=0”),例如:
#include <iostream>
class Base {
public:
virtual void foo() = 0;
};
class Derived : public Base {
public:
void foo() { std::cout << "Derived::foo()" << std::endl; }
};
int main(int argc, char** argv) {
Base* pb = new Derived();
pb->foo(); // call Derived::foo()
}
Java语言中,接口函数与C++中的纯虚函数类似,例如:
interface Base {
public void foo();
}
class Derived implements Base {
public void foo() { System.out.println("Derived::foo()"); }
}
class Main {
public static void main(String argv[]) {
Base pb = new Derived();
pb.foo(); // call Derived::foo()
}
}
Java类中如何实现“纯虚函数”呢?
答案是:使用abstract关键字,例如:
abstract class Base {
public abstract void foo();
}
class Derived extends Base {
public void foo() { System.out.println("Derived::foo()"); }
}
class Main {
public static void main(String argv[]) {
Base pb = new Derived();
pb.foo(); // call Derived::foo()
}
}
说明:
- Java中的“纯虚函数”叫做抽象方法。
- Java类中若包含抽象方法,则声明类时必须使用abstract关键字将类标记为抽象类。
- Java中抽象类与C++中抽象类一样,区别在于:
- C++中,只要类中有一个纯虚函数,该类即为抽象类;
- 而Java中需要显式地声明该类为抽象类,并且Java抽象类中不必须包含抽象方法。
参考:https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html