C++与Java中的继承
在C++和Java中,都有继承的概念。继承特性用于代码重用,并在两个对象之间建立关系。在这里,我们将看到C++和Java中继承的一些基本区别。
在Java中,所有类都扩展了Object类。因此,类始终只有一个级别的继承树。Object类位于树的根部。让我们使用简单的代码检查这是否属实。
示例
//This is present in the different file named MyClass.java
public class MyClass {
MyClass() {
System.out.println("This is constructor of MyClass.");
}
}
//This is present the different file named Test.Java
public class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.println("obj is an instance of Object: " + (obj instanceof Object));
}
}输出
This is constructor of MyClass. obj is an instance of Object: true
在Java中,无法直接访问祖父母类的成员。
与C++相比,Java中的受保护可见性略有不同。在Java中,基类的受保护成员可以从同一包中的另一个类访问,即使该类不是从基类派生的。这里MyClass的受保护成员可以从Test访问。
示例
//This is present in the different file named MyClass.java
public class MyClass {
protected int x = 10;
protected int y = 20;
}
//This is present the different file named Test.Java
public class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.println("x is: " + obj.x + " y is: " + obj.y);
}
}输出
x is: 10 y is: 20
在Java中,我们使用extends关键字进行继承。在C++中,我们可以确定继承的可见性,例如public、protected和private,但在这里我们无法更改可见性。因此,如果基类中某个成员是public或protected,那么在派生类中它们也将是public或protected。
在Java中,所有方法默认都是虚拟的。在C++中,我们必须指定virtual关键字。
在C++中,我们可以使用多重继承。在Java中,我们不能直接创建多重继承。为了减少歧义,Java支持接口来实现多重继承的效果。接口纯粹是抽象基类,没有任何函数是完整的,因此没有歧义。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP