简体   繁体   中英

Java - Inheritance (Base & Child)

在Java文件中,假设有2个类-类A和B,我们可以在类B中创建类A的对象并可以调用类A的方法。那么为什么我们需要继承类A,例如“类B扩展了类A”因为我们可以通过在B类中创建A对象来调用A类方法?

Think about the real world: a Dog is a Mammal. It doesn't contain one! In such situations it can make more sense for Dog to extend Mammal.

One key use case is that the base class implements certain behaviors (methods) that a child class needs to have, too. Then inheritance is one possible solution.

But you are correct in the sense that composition is often preferred over inheritance.

Also note: Java is a statically compiled language. Therefore it is really important to express such relationships on a type level. In contrast to dynamic languages, Java has no concept of declaring (at runtime): this object here has a quack() method, so let's assume the object is of type Duck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM