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