Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner Classes vs. Subclasses in Java

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)?

like image 364
Joel J. Avatar asked Oct 29 '15 17:10

Joel J.


2 Answers

There are big differences between inner classes and subclasses:

  • inner classes are in the same file, whereas subclasses can be in another file, maybe in another package.
  • You cannot get an instance of an inner class without an instance of the class that contains it.
  • inner classes have the methods they want, whereas subclasses have the methods of their parent class. Subclasses can of course define additional methods, but they'll always have those of their parent.

About the situation:

  • inner classes are used when your big class needs a (usually short) class, related to its internal operation, and when nobody else needs it. A good example Nik G quoted is the LinkedList: it needs a Node class to work, that is short, and that no other class needs. Therefore Node is an inner class of LinkedList.
  • subclasses are used when you defines a "is-a" reliationship. Picture this: you want to make different types of cars. They have common properties and features: they all can move, they all have passengers, etc. So you create an abstract class "Car" with these common things. And you create a subclass for every different type of car.
like image 169
ElectronWill Avatar answered Sep 23 '22 09:09

ElectronWill


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.

like image 43
MrBlueSky Avatar answered Sep 26 '22 09:09

MrBlueSky