Significant amount of the time, I can't think of a reason to have an object instead of a static class. Do objects have more benefits than I think?

Posted by Prog on Programmers See other posts from Programmers or by Prog
Published on 2014-06-03T21:17:07Z Indexed on 2014/06/03 21:38 UTC
Read the original article Hit count: 151

Filed under:
|
|
|

I understand the concept of an object, and as a Java programmer I feel the OO paradigm comes rather naturally to me in practice.

However recently I found myself thinking:

Wait a second, what are actually the practical benefits of using an object over using a static class (with proper encapsulation and OO practices)?

I could think of two benefits of using an object (both significant and powerful):

  1. Polymorphism: allows you to swap functionality dynamically and flexibly during runtime. Also allows to add new functionality 'parts' and alternatives to the system easily. For example if there's a Car class designed to work with Engine objects, and you want to add a new Engine to the system that the Car can use, you can create a new Engine subclass and simply pass an object of this class into the Car object, without having to change anything about Car. And you can decide to do so during runtime.

  2. Being able to 'pass functionality around': you can pass an object around the system dynamically.

But are there any more advantages to objects over static classes?

Often when I add new 'parts' to a system, I do so by creating a new class and instantiating objects from it.

But recently when I stopped and thought about it, I realized that a static class would do just the same as an object, in a lot of the places where I normally use an object.

For example, I'm working on adding a save/load-file mechanism to my app.

With an object, the calling line of code will look like this: Thing thing = fileLoader.load(file);

With a static class, it would look like this: Thing thing = FileLoader.load(file);

What's the difference?

Fairly often I just can't think of a reason to instantiate an object when a plain-old static-class would act just the same. But in OO systems, static classes are fairly rare. So I must be missing something.

Are there any more advantages to objects other from the two that I listed? Please explain.

© Programmers or respective owner

Related posts about design

Related posts about object-oriented