Java继承说明

遗产 (Inheritance)

Java inheritance refers to the ability of a Java Class to inherit the properties from some other Class. Think of it like a child inheriting properties from its parents, the concept is very similar to that. In Java lingo, it is also called extend-ing a class.

Java继承是指Java类从其他类inherit属性的能力。 认为它就像孩子从父母那里继承财产一样,这个概念与此非常相似。 在Java语言中,它也称为扩展-类。

Some simple things to remember:

一些简单的事情要记住:

  • The Class that extends or inherits is called a subclass

    扩展或继承的称为子类

  • The Class that is being extended or inherited is called a superclass

    被扩展或继承的称为超类

Thus, inheritance gives Java the cool capability of re-using code, or sharing code between classes!

因此,继承为Java提供了很酷的功能,可以重用代码或在类之间共享代码!

Let’s describe it with the classic example of a Vehicle class and a Car class :

让我们用Vehicle类和Car类的经典示例来描述它:

public class Vehicle {
    public void start() {
        // starting the engine
    }

    public void stop() {
        // stopping the engine
    }
}

public class Car extends Vehicle {
    int numberOfSeats = 4;

    public int getNumberOfSeats() {
        return numberOfSeats;
    }
}

Here, we can see the Car class inheriting the properties of the Vehicle class. So, we don’t have to write the same code for the methods start() and stop() for Car as well, as those properties are available from its parent or superclass. Therefore, objects created from the Car class will also have those properties!

在这里,我们可以看到Car类继承了Vehicle类的属性。 因此,我们不必为Car start()stop()方法编写相同的代码,因为这些属性可从其父类或超类获得。 因此,从Car类创建的对象将具有这些属性!

Car tesla = new Car();

tesla.start();

tesla.stop();

Run Code

运行代码

But, does the parent class have the methods of the child? No, it doesn’t.

但是,父类是否具有子类的方法? 不,不是。

Therefore, whenever you need to share some common piece of code between multiple classes, it is always good to have a parent class, and then extend that class whenever needed! Reduces the number of lines of code, makes code modular, and simplifies testing.

因此,每当需要在多个类之间共享一些通用代码时,最好有一个父类,然后在需要时扩展该类! 减少代码行数,使代码模块化,并简化测试。

有什么可以继承的? (What can be inherited ?)

  • All protected and public fields and methods from parent

    父级的所有protected public字段和方法

什么不能被继承? (What cannot be inherited ?)

  • private fields and methods

    private领域和方法

  • Constructors. Although, the subclass constructor has to call the superclass constructor if its defined (More on that later!)

    构造函数。 不过,如果子类构造函数定义, 必须调用超类构造函数(稍后会有更多说明!)

  • Multiple classes. Java supports only single inheritance, that is, you can only inherit one class at a time.

    多个类。 Java仅支持单一继承 ,也就是说,一次只能继承一个类。

  • Fields. Individual fields of a class cannot be overriden by the subclass.

    领域。 子类不能覆盖类的各个字段。

类型转换和参考 (Type Casting & Reference)

In Java, it is possible to reference a subclass as an instance of its superclass. It is called Polymorphism in Object Oriented Programming (OOP), the ability for an object to take on many forms. For example, the Car class object can be referenced as a Vehicle class instance like this :

在Java中,可以将子类引用为其超类的实例 。 在面向对象程序设计(OOP)中,它被称为多态性 ,即对象具有多种形式的能力。 例如, Car类对象可以被引用为Vehicle类实例,如下所示:

Vehicle car = new Car();

Although, the opposite is not possible :

虽然,相反是不可能的:

Car car = new Vehicle(); // ERROR

Run Code

运行代码

Since you can reference a Java subclass as a superclass instance, you can easily cast an instance of a subclass object to a superclass instance. It is possible to cast a superclass object into a subclass type, but only if the object is really an instance of the subclass. So keep this in mind :

由于您可以将Java子类引用为超类实例,因此可以轻松地将子类对象的实例转换为超类实例。 可以将超类对象转换为子类类型,但前提是该对象确实是subclass的实例 。 因此请记住这一点:

Car car = new Car();
Vehicle vehicle = car; // upcasting
Car car2 = (Car)vechile; //downcasting

Bike bike = new Bike(); // say Bike is also a subclass of Vehicle
Vehicle v = bike; // upcasting, no problem here.
Car car3 = (Car)bike; // Compilation Error : as bike is NOT a instance of Car

Run Code

运行代码

Now you know how to share code through a parent-child relationship. But, what if, you do not like the implementation of a particular method in the child class and want to write a new one for it? What do you do then?

现在,您知道了如何通过父子关系共享代码。 但是,如果您不喜欢子类中特定方法的实现并想为其编写一个新方法,该怎么办? 那你怎么办呢?

覆盖它! (Override it!)

Java lets you override or redefine the methods defined in the superclass. For example, your Car class has a different implementation of start() than the parent Vehicle, so you do this :

Java使您可以重写或重新定义超类中定义的方法。 例如,您的Car类与父Vehicle具有不同的start()实现,因此您可以这样做:

public class Vehicle {
    public void start() {
      System.out.println("Vehicle start code");
    }
}

public class Car extends Vehicle {
    public void start() {
      System.out.println("Car start code");
  }
}

Car car = new Car();
car.start(); // "Car start code"

Run Code

运行代码

So, it’s pretty simple to override methods in the subclass. Although, there is a catch. Only that superclass method with the exact same method signature as the subclass method will be overriden. That means the subclass method definition must have the exact same name, same number and type of parameters, and in the exact same sequence. Thus, public void start(String key) would not override public void start().

因此,覆盖子类中的方法非常简单。 虽然有一个陷阱 。 只有具有与子类方法完全相同的方法签名的超类方法将被覆盖。 这意味着子类方法定义必须具有完全相同的名称,相同的参数编号和类型,并具有完全相同的顺序。 因此, public void start(String key)不会覆盖public void start()

Notes :

注意事项

  • You cannot override private methods of the superclass. (Quite obvious, isn’t it?)

    您不能覆盖超类的私有方法。 (很明显,不是吗?)
  • What if the method of superclass which you are overriding in the subclass suddenly gets obliterated or methods changed? It would fail in runtime! So Java provides you a nifty annotation @Override which you can place over the subclass method, which will warn the compiler of those incidents!

    如果您在子类中重写的超类方法突然消失或方法改变了怎么办? 它将在运行时失败! 因此,Java为您提供了一个漂亮的注释@Override ,您可以将其放在子类方法上,这将警告编译器这些事件!

Annotations in Java is a good coding practice, but they are not a necessity. The compiler is smart enough to figure out overriding on its own though. Unlike other OOP languages, Annotations in Java it doesn’t necessarily modify the method or add extra functionality.

Java中的注释是一种很好的编码实践,但不是必须的。 编译器足够聪明,尽管可以自己找出覆盖。 与其他OOP语言不同,Java中的注释不必修改方法或添加其他功能。

如何调用超类方法? (How to call super class methods?)

Funny you ask about it! Just use the keyword super :

有趣的是你问这个! 只需使用关键字super

public class Vehicle() {
    public void start() {
      System.out.println("Vehicle start code");
    }
}

public class Car extends Vehicle {
    public void run() {
      super.start();
  }
}

Car car = new Car();
car.run(); // "Vehicle start code"

Run Code

运行代码

N.B. : Although you can call the parent method by using a super call, you cannot go up the inheritance hierarchy with chained super calls.

注意 :尽管您可以使用super调用来调用父方法,但是您无法使用链接的super调用进入继承层次结构。

如何知道班级的类型? (How to know the type of a class?)

Using the instanceof keyword. Having lots of classes and subclasses it would be a little confusing to know which class is a subclass of which one in runtime. So, we can use instanceof to determine whether an object is an instance of a class, an instance of a subclass, or an instance of an interface.

使用instanceof关键字。 拥有很多类和子类,在运行时知道哪个类是哪个子类的子类会有些困惑。 因此,我们可以使用instanceof来确定对象是类的实例,子类的实例还是接口的实例。

Car car = new Car();

boolean flag = car instanceof Vehicle; // true in this case!

构造函数与继承 (Constructors & Inheritance)

As mentioned earlier, constructors cannot be directly inherited by a subclass. Although, a subclass is required to call its parent’s constructor as the first operation in its own constructor. How? You guessed it, using super :

如前所述,构造函数不能直接由子类继承。 虽然,子类需要调用其父级的构造函数作为其自身构造函数中的第一个操作 。 怎么样? 您猜对了,使用super

public class Vehicle {
    public Vehicle() {
        // constructor
    }
    public void start() {
      System.out.println("Vehicle start code");
    }
}

public class Car extends Vehicle {
    public Car() {
      super();
    }
    public void run() {
      super.start();
  }
}

Run Code

运行代码

Remember, if the superclass does not have any constructors defined, you don’t have to call it explicitely in the subclass. Java handles that internally for you! Invocation to super constructor is done in the case when the super class is to be called with any other constructor other than the default constructor.

请记住,如果超类没有定义任何构造函数,则不必在子类中显式调用它。 Java在内部为您处理! 如果要用默认构造函数以外的任何其他构造函数调用super类,则将调用super构造函数

If no other constructors are defined, then Java invokes the default super class constructor (even if not defined explicitly).

如果没有定义其他构造函数,则Java会调用默认的超类构造函数( 即使未显式定义 )。

Congrats, now you know all about Inheritance! Read more about advanced ways to inherit things in Abstract Classes and Interfaces!

恭喜,现在您已经了解继承! 阅读有关在Abstract类和接口中继承事物的高级方法的更多信息!

翻译自: https://www.freecodecamp.org/news/inheritance-in-java-explained/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值