C++与java继承的比较

继承的目的在C++和java中是相同的。继承在两种语言中都用于重用代码和/或创建“is-a”关系。下面的示例将演示java和C++之间的差异,这些差异为继承提供支持。

null

1) 在Java中,所有类都继承自 对象类 直接或间接。 因此,Java中总是有一个单一的类继承树,而对象类是树的根。在Java中,当创建一个类时,它会自动从对象类继承。在C++中,有一个类的森林;当我们创建一个不从其他类继承的类时,我们会在林中创建一棵新树。

下面的Java示例显示 考试班 自动从对象类继承。

JAVA

class Test {
// members of test
}
class Main {
public static void main(String[] args)
{
Test t = new Test();
System.out.println( "t is instanceof Object: "
+ (t instanceof Object));
}
}


输出

t is instanceof Object: true

2) 在Java中,祖父母类的成员不能直接访问。 (参考 更多细节,请参阅本文)。

3) 受保护的成员访问说明符在Java中的含义有些不同。 在Java中,类“a”的受保护成员可以在同一个包的其他类“B”中访问,即使B不是从a继承的(它们必须在同一个包中)。

例如,在下面的程序中,A的受保护成员可以在B中访问。

JAVA

class A {
protected int x = 10 , y = 20 ;
}
class B {
public static void main(String args[])
{
A a = new A();
System.out.println(a.x + " " + a.y);
}
}


输出

10 20

4) Java使用“扩展” 用于继承的关键字。 与C++不同,java不提供公共、受保护或私有的继承说明符。因此,我们不能在Java中更改基类成员的保护级别,如果某个数据成员在基类中是公共的或受保护的,那么它在派生类中仍然是公共的或受保护的。和C++一样,基类的私有成员在派生类中是不可访问的。

与C++不同,在java中,我们不必记住继承的基本规则,这些规则是基类访问说明符和继承说明符的组合。

5) 在Java中,默认情况下方法是虚拟的。在C++中,我们明确地使用虚拟关键字 (参考 更多细节,请参阅本文)。

6) Java使用一个单独的关键字 界面 接口和 摘要 抽象类和抽象函数的关键字。

下面是一个Java抽象类示例,

JAVA

// An abstract class example
abstract class myAbstractClass {
// An abstract method
abstract void myAbstractFun();
// A normal method
void fun() { System.out.println( "Inside My fun" ); }
}
public class myClass extends myAbstractClass {
public void myAbstractFun()
{
System.out.println( "Inside My fun" );
}
}


下面是一个Java接口示例,

JAVA

// An interface example
public interface myInterface {
// myAbstractFun() is public
// and abstract, even if we
// don't use these keywords
void myAbstractFun();
// is same as public abstract void myAbstractFun()
}
// Note the implements keyword also.
public class myClass implements myInterface {
public void myAbstractFun()
{
System.out.println( "Inside My fun" );
}
}


7) 与C++不同,java不支持多个继承。 一个类不能从多个类继承。然而,一个类可以实现多个接口。

8) 在C++中,父类的默认构造函数被自动调用,但是如果我们要调用父类的参数化构造函数,必须使用 初始化成员列表 和C++一样,父类的默认构造函数在java中自动调用,但是如果我们要调用参数化构造函数,那么我们必须使用Sub来调用父构造函数。请参见下面的Java示例。

JAVA

package main;
class Base {
private int b;
Base( int x)
{
b = x;
System.out.println( "Base constructor called" );
}
}
class Derived extends Base {
private int d;
Derived( int x, int y)
{
// Calling parent class parameterized constructor
// Call to parent constructor must be the first line
// in a Derived class
super (x);
d = y;
System.out.println( "Derived constructor called" );
}
}
class Main {
public static void main(String[] args)
{
Derived obj = new Derived( 1 , 2 );
}
}


输出

Base constructor calledDerived constructor called

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享