Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will inheritance break encapsulation?

Let's say I have a CSV file and I create a class called CsvFile which extends from java.io.File. This class can parse a CSV file and return some data like how many columns are in the file. It can also be used for functions which takes java.io.File as input. Like FileUtils.copyFile(File from, File to).

My colleague thinks I expose too much from inheritance. His idea is to wrap java.io.File by holding it in a private property, instead of inheriting it. He think exposing all public method/property from file breaks encapsulation, but I take it as a benefit since we get all functions in java.io.File for free.

What do you think?

like image 265
Frank Avatar asked Jun 27 '12 01:06

Frank


2 Answers

I would rather agree with your colleague: inheriting java.util.File would expose methods that are not applicable to CsvFile objects, such as list(), listFiles(), setExecutable(), and so on.

Making java.util.File a property behind a getter sounds like a better choice: it does not reveal irrelevant operations to the users of your class, and lets you inherit from a base class of your choice.

like image 179
Sergey Kalinichenko Avatar answered Sep 22 '22 05:09

Sergey Kalinichenko


I think it all depends of the purpose of the class. If you are truly trying to extend the behavior then I would say it makes sense. If you are not extending behavior of File but are just making a CSV object then encapsulation would limit its behaviors to only what it intention is.

like image 29
WeeJavaDude Avatar answered Sep 22 '22 05:09

WeeJavaDude