简体   繁体   中英

Java Inheritance: should an extension of a class inherit the class?

For my current project, I'm making a wrapper for the java File class, as well as a wrapper for a path String (ie. C:\\Users\\Public\\ ). Let's call the wrapper for the File class FileWrapper and the wrapper for a path PathWrapper .

FileWrapper obviously must have a path: the location of FileWrapper 's File on the disk. Now my question is... Should FileWrapper contain a field of type PathWrapper (and an accessor method for PathWrapper 's PathWrapper.getPath() ), or should it extend PathWrapper , therefore inheriting the getPath() method?

The issue I'm having is that FileWrapper , strictly speaking, isn't a Path . It's just a file. But it seems simpler to just use inheritance anyway in this case.

There is another issue with the second solution I was considering (create a getPath() method in FileWrapper ). I would like to create a Path interface that FileWrapper and PathWrapper would both implement, in order to allow generic lists of both FileWrapper s and PathWrapper s. If FileWrapper was a subclass of PathWrapper , this interface would not be necessary.

OO Design Rule : Favor Composition over inheritence, as composition (Has-a relations) allows more flexibility to your code

Also as you say, FileWrapper is not a PathWrapper , you answered your question.

You want to bind them together, you can pass a PathWrapper to the constructor of the FileWrapper .

For example, if you want to get both in a Collection , you can make a Wrapper interface, where FileWrapper and PathWrapper are siblings in this hierarchy, and share common abstract methods that can be implemented differently by each of them.

Many design patterns can be applied to this example, all what you need to do is decide what you want first.

The issue I'm having is that FileWrapper , strictly speaking, isn't a Path . It's just a file.

That's the only consideration that you need: once you say that logically a FileWrapper is not a Path , you should exclude inheritance from your list of choices.

That is not to say that you shouldn't give FileWrapper a getPath method, though: if you find it more convenient to have getPath right on the FileWrapper class, then it makes perfect sense to add the method.

I would like to create a "Path" interface that FileWrapper and PathWrapper would both implement, in order to allow generic lists of both FileWrappers and PathWrappers .

That sounds like a good idea. An interface is a nice, lightweight alternative to subclassing that makes more sense in your situation. Properly named, such an interface would add clarity to your overall system, without adding confusion associated with doubtful inheritance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM