Java 的 interface、abstract class 与 C++ 的多继承、虚基类

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 关键字!

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值