Search code examples
javaclassoopinheritancenested-class

Java - Superclass (Inheritance) vs Parent class (no Inheritance)


newbie here, preparing for job interviews.

I'm reading and practicing object-oriented programming concepts, however I'm stuck on why inheritance is important at all when (in Java) we can create member classes...

For example, Oracle's official Java tutorial, gives examples of bikes, that although there are many characteristics that are common with different types of bikes (Mountain, road or tandem bikes) but they all have their own unique different characteristics too. So to implement this, we create a class Bikes, which has all the common characteristics, and then separate classes for Mountain, road and tandem bikes, all of which inherit the bike class. Something like this....

class Bike {
     int speed;
     int gear;
}

class MountainBike extends Bike {
     int chain rings;
}

//classes for road bike and tandem bike etc...

Isn't it the same thing as following?

class Bike {
     int speed;
     int gear;

     class MountainBike {
         int chain rings;
     }

     //classes for Road bike or tandem bike etc...
}

I mean an instance created of the class MountainBike will have characteristics speed and gear too, right? And that was the whole point of inheritance, i.e. to reduce redundant data by eliminating the need to create separate data members which are common to many objects. So why do we need inheritance at all?

Thanks for your patience...


Solution

  • The first example says that every MountainBike is a Bike. This is how it should be.

    The second example says that every MountainBike belongs to a Bike. This makes no sense at all. For example, with your second example you could write

    Bike bike = new Bike();
    Bike.MountainBike mountainBike1 = bike.new MountainBike();
    Bike.MountainBike mountainBike2 = bike.new MountainBike();
    

    This would create a new Bike called bike and two MountainBikes that belong to bike.

    Something that would make sense as an inner class of Bike would be Wheel. Then you could write

    Bike bike = new Bike();
    Bike.Wheel frontWheel = bike.new Wheel();
    Bike.Wheel backWheel = bike.new Wheel();
    

    Then you would have a Bike with two Wheels that belong to the Bike.