Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...