Java 与 C++ 的主要区别
1.Java 堆栈内存均自动托管,C++ 需要人工管理堆内存;
2.Java 支持反射,C++ 不支持反射;
3.Java 单继承,只能通过 interface 实现多继承;C++ 支持多继承,并且支持虚继承。
4.Java 不支持作用域内变量重名,用包名区分,没有全局变量;C++ 支持作用域内变量重名,使用名字空间区分,有全局变量,所谓的全局变量其实质为 domain 名字空间;
5.Java 支持嵌套类,类与类的关系可以是非平行关系,内部类可以访问外部类的成员变量,C++ 中所有类都是平行关系,伪嵌套关系可以通过友元实现!
表面上的代码差异
1.C++ 类与 Java 类的对比:
// C++ class
class Parent
{
public:
static int staticValue = 0;
public:
void Method1()
{
cout << "C++ class!\n";
}
};
class Test
: public Parent
{
private:
int value1;
const float value2 = 3.4;
static void* value3 = nullptr;
public:
static const int value4 = 5;
public:
void Method1()
{
cout << Parent::staticValue << endl;
this->Parent::Method1();
}
static void Method2()
{
cout << value4 << endl;
}
};
// Java class
public class Parent
{
public static int static_value = 0;
public void method1()
{
System.out.println("Java class!");
}
}
public class extends Parent
{
private int value1;
private final float value2 = 3.4;
private static String value3 = null;
public static final int value4 = 5;
public void method1()
{
System.out.println(Parent.static_value);
super.method1();
}
public static method2()
{
System.out.println(value4);
}
}
2.C++ 与 Java 多态比较:
// Java 多态
public class TestJava {
public static void main(String args[]) {
abstract class Animal {
public void eat() {
System.out.println("吃");
}
public abstract void action();
}
class Dog extends Animal {
public void eat() {
System.out.println("狗吃屎");
}
public void action() {
System.out.println("狗吠");
}
public void work() {
System.out.println("狗拿耗子");
}
}
class Cat extends Animal {
public void eat() {
System.out.println("猫吃鱼");
}
public void action() {
System.out.println("猫卖萌");
}
public void work() {
System.out.println("猫在叫");
}
}
Animal a = new Dog();
a.eat();
a.action();
if (a instanceof Dog)
((Dog)a).work();
}
}
注意,C++ 使用 typeid,java 使用 instanceof 关键字!