简体   繁体   中英

Walking Both Ways of The Inheritance Chain

Sorry if I do a bad job of phrasing this, I'm trying my best. In Object Oriented programming, the is-a relationship is commonly used in discussions (talked about? not sure how to say it). However, is there ever a useful purpose in going up the inheritance chain? Starting from the child, then walking all the way back up? The only situation I can think of is something like this:

public class A {
    public void sayHi(){
        System.out.println("Hi, from A");
    }
}

public class B extends A{
    public void sayHi(){
        System.out.println("Hi, from B");
    }
}
public class C extends B{
    //no overriden version for C
}

Here, you walk up the chain to find the closest version of sayHi there is, which for object myObject would be residing in B

A myObject = new C();
myObject.sayHi(); //Hi, from B

Are there any other useful ways of analyzing relationships while walking up the inheritance chain?

NOTE:

Although it may not have an impact, I'm asking this question from a Java frame of mind

This can be useful when you need to analyze metadata attached to a superclass.

For two concrete examples, database classes (such as JPA entities and Spring Data documents) frequently have some core metadata, such as the MongoDB collection to use, on the base class, along with additional information on concrete subclasses. Additionally, service objects (such as Spring MVC controllers) may have mappings or security annotations listed on a base class. The container needs to walk up the hierarchy to merge the appropriate rules in either case.

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