快去自定义签名吧~|

Mozziemy

园龄:1年6个月粉丝:0关注:0

C#与Java的继承与实现上的差异

虽然 C# 和 Java 都支持继承和接口实现这两种面向对象编程的基本概念,但它们在一些细节上有一些差异。

继承(Inheritance)

  1. 单继承 vs 多继承

    • C# 支持单继承,一个类只能直接继承自一个父类。
    • Java 也支持单继承,一个类只能直接继承自一个父类。
  2. 基类构造函数的调用

    • 在 C# 中,如果子类没有显式调用基类构造函数,将自动调用基类的无参数构造函数。如果需要显式调用基类的构造函数,可以使用 base 关键字。
    • 在 Java 中,子类构造函数总是会调用父类的构造函数,如果没有显式调用,将调用父类的无参数构造函数。如果需要显式调用父类的构造函数,可以使用 super 关键字。
  3. 构造函数的调用顺序

    • 在 C# 中,构造函数的调用顺序是自底向上的,即先调用基类的构造函数,然后再调用子类的构造函数。
    • 在 Java 中,构造函数的调用顺序是自顶向下的,即先调用父类的构造函数,然后再调用子类的构造函数。

代码对比:

C# 中的继承

using System;

class Animal
{
    public virtual void Sound()
    {
        Console.WriteLine("Animal makes a sound");
    }
}

class Dog : Animal
{
    public override void Sound()
    {
        Console.WriteLine("Dog barks");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dog dog = new Dog();
        dog.Sound(); // 输出 "Dog barks"
    }
}

Java 中的继承

class Animal {
    public void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.sound(); // 输出 "Dog barks"
    }
}

接口实现(Implementation)

  1. 默认方法

    • 在 Java 8 中,接口可以包含默认方法,这是一种在接口中提供默认实现的方式,可以减少实现接口的类的代码量。
    • 在 C# 中,接口不支持默认方法,所有的接口方法都需要在实现类中提供具体的实现。
  2. 方法签名

    • 在 Java 中,接口方法默认是公共的抽象方法,实现类必须提供具体实现。
    • 在 C# 中,接口方法默认是公共的虚方法,实现类可以选择重写这些方法,也可以选择不重写。
  3. 多继承

    • 在 Java 中,类只能继承自一个类,但可以实现多个接口。
    • 在 C# 中,类只能继承自一个类,并且可以实现多个接口。

代码对比

C# 中的接口实现

using System;

interface IShape
{
    double GetArea();
}

class Rectangle : IShape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public double GetArea()
    {
        return Width * Height;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Rectangle rectangle = new Rectangle { Width = 5, Height = 10 };
        Console.WriteLine("Area of rectangle: " + rectangle.GetArea()); // 输出 "Area of rectangle: 50"
    }
}

Java 中的接口实现

interface IShape {
    double getArea();
}

class Rectangle implements IShape {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double getArea() {
        return width * height;
    }
}

public class Main {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle(5, 10);
        System.out.println("Area of rectangle: " + rectangle.getArea()); // 输出 "Area of rectangle: 50.0"
    }
}

本文作者:Mozziemy

本文链接:https://www.cnblogs.com/mozziemy/p/18036275

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Mozziemy  阅读(106)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起