Class declaration in Java

Asked

Viewed 85 times

3

I can declare more than one class in the same Java file, and if this is possible, it is the most correct way to program in this language?

  • 2
  • I recommend reading this linked topic.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

2 answers

4

Yes, it is perfectly possible and makes sense if the classes are very related, because only one of the classes can be public.

That kind of thing is not right without seeing the context. There are those who recommend putting one class per file, and it is a good recommendation, but not that it should always be followed. Let’s say it’s not common, but it can when the other classes aren’t so important.

  • 2

    Just an example, the google maps api returns a json that can be converted to a java object, some of the child objects (I don’t know if that’s the proper term) are very simple (2 or 3 fields) and can be put together to another class to avoid 20 and a few files just to convert the return of the api

1

Yes it is possible, but it should be used carefully, especially if we think about maintaining it, imagine that as the project grows these classes can change its scope and in practice, you (or another team programmer) will hardly remember to modify this structure.

I suggest reading of that Article about cohesion and coupling, this will help you when modeling your classes.

So you can use it, but you should analyze if it really makes sense for your project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.