Is there a situation where it is more beneficial to use an inner class over a subclass in Java (or vice-versa)? Based on my current understanding, inner classes have access to the fields and methods of the outer class. How is this any different from using inheritance?
Subclasses generally have access to all the fields/methods labeled public and protected. Fields labeled private in the parent class can be accessed in the subclass using a getter method. Based off what I've seen thus far, when methods are labeled private, they're usually called in other methods of the class that are labeled either public or protected. Granted, I'm not an experienced Java programmer, but that seems to be the general trend.
Based on my current understanding, there seems to really be no benefit between choosing one over the other. Can someone give insight as to why and when I should use an inner class over inheritance (or vise versa)?
There are big differences between inner classes and subclasses:
About the situation:
A subclass inherits it's parent class' variables and methods, an inner class doesn't.
Therefor, you would want to use a subclass when the child class should have it's parent's members and use inner class when you only need it to perform it's part.
e.g you would use a an inner class named Node in a class named List so you can use Node as a member.
e.g you would use a subclass named Mercedes in a class named Car, as a Mercedes should inherit the members of a Car and override Car's methods if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With