• Post Reply Bookmark Topic Watch Topic
  • New Topic

segmenting java files  RSS feed

 
Arul Jose
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchies,

Is there a way to keep the code for one class in multiple files?

say like having the code for Utils.java in Utils0.java, Utils1.java, Utils2.java etc.

arul jose
 
Philip Shanks
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think so, and I can't think of a reason to do that, but then perhaps I'm just not that creative.

A *.java file contains the source for a compilation unit, which in turn contains the definition of a class or interface. The compiled byte code goes into the corresponding *.class file.

The standard method for distributing the ultimate definition of a specific class is to use the Java inheritance mechanisms.

For instance, you might define an abstract or some base class, and then extend that to implement the specific functionality that is required.

Or you might create one or more interfaces that define the messages shared between classes.

The bottom line is this: a class can be subdivided into component units (the "has a" relationship) and/or identity units (the "is a" relationship, usually facilitated by interfaces). But I don't think that the Java language specification makes allowances for a class to be sliced up like a block of cheese.
[ February 09, 2007: Message edited by: Philip Shanks ]
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you cannot split the code for one class over multiple source files. The Java compiler requires that all the code for a class is in a file that has the same name as the class. This helps to keep your project organized and makes it easy to find the source code for a class - you know immediately in which source file you need to look.

What is your reason for wanting to split the source of a class over multiple files? Is the class you are writing getting really big (thousands of lines of code)? If that's the case, then you should think about refactoring your code.

You are talking about an "Utils" class. What does that class contain? Does it contain lots of different utility methods for lots of different purposes? Maybe you should have a look at all those methods and find out which of them belong together. For example, you might want to move all the methods that do things with strings to a class StringUtils, and the methods that do things with dates to a class DateUtils, etc.

(Interestingly, you can do this in Microsoft's C# - you can write "partial" classes. The main reason why this exists in C# is to separate automatically generated code for GUI components from user-written code).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!