Search code examples
javainheritancesubtyping

JAVA: are the notion of subtyping and of inheritance the same thing?


Based on the note at the end of this answer it looks like subtyping and inheritance are subtly different concepts in Java. What is it? Is inheritance only when a class declaration contains an extends ... clause? If this is the case then a class will not inherit from Object, even if it is a subtype of it, right?


Solution

  • Inheritance is a way to achieve subtyping. Taken from Wikipedia:

    In programming language theory, subtyping (also subtype polymorphism or inclusion polymorphism) is a form of type polymorphism in which a subtype is a datatype that is related to another datatype (the supertype) by some notion of substitutability, meaning that program elements, typically subroutines or functions, written to operate on elements of the supertype can also operate on elements of the subtype.

    In short, let's look at this:

    class Super {
    }
    
    class Child extends Super {
    }
    

    This is inheritance, because Child inherits everything from Super.

    Super super = new Child();
    

    This is subtyping, because we are referring to Child as a Super. So you should see what I mean when I say that Inheritance allows you to perform subtyping, but they are not the same thing.

    For example, you can achieve subtyping with interfaces:

    class Child extends Super implements ISomeInterface {
    }
    

    Now we can refer to Child as:

    ISomeInterface someInterface = new Child();
    

    Here, we're referring to it as the type ISomeInterface, without the need for an inheritance relationship.

    Your Questions

    All Objects in Java are subclasses of type Object. They implicitly have extends Object in their class header. It's just the way the language works. So yes, every object is a subtype of class Object.

    In Java, inheritance is only available through the use of the extends keyword.

    Extra Reading

    Edit

    Listen to everything Marko Topolnik says. He is pretty smart you know.