Is there a way to do partial classes in Java (like C#)?

13.8k views Asked by At

C# has this great concept where a class can be spread across multiple .cs files. This works great where you want a single object (member variables that all the code needs) but there's a ton of code. You can then spread this code out by functionality across source files.

Is there a way to do this in Java?

Update: Ok at first I told myself that this must be a single large class (it performs layout of the content of a DOCX file). But then after posting this I thought about it more and it really bothered me that it is this one large (5,000+ lines at present) class.

So I thought through some alternatives and came up with a good way to break it out into one main class and about 20 helper classes. It works very well this way really separating out the functionality into each part.

So... while I think partial classes is a useful construct at times, in this case the lack of partial classes caused me to come up with a better design. (And this has nothing to do with the initial question, but I thought it was worth sharing.)

5

There are 5 answers

1
Dylan On

No, Java doesn't support partial classes.

If this is just idle curiosity, check out Scala. It compiles to .class files just like Java, and has full interop. It supports a rough equivalent of partial classes as "traits".

An example of trait usage:

trait FunctionalityA {
  // some stuff implemented here
}

trait FunctionalityB {
  // more stuff implemented...
}

// etc...

class MyBigClass extends FunctionalityA with FunctionalityB with FunctionalityC
0
Asaph On

No. Java does not support partial classes. You'll find more in depth discussion in this question and this question.

0
PNS On

There is no way to have partial class definitions, spread across files. Every class must be defined in its own namesake file.

On the contrary, you can define additional classes within that file and within the (top level) class definition.

2
lostinexceptions On

No, it is one of the wonderful features in Java. A Class must be identical with her filename. :-)

0
chrvip On

I find a way to emulate C# partial class depend on @Delegate in lombok

@Getter 
@Setter
public class User {
    String name;
    @Delegate
    private UserDelegate delegate= new UserDelegate(this);
}
public class UserDelegate {
  private User expandOwner;

  public UserDelegate(User expandOwner) {
    this.expandOwner = expandOwner;
  }

  public void doSomethinga() {
    System.out.println(expandOwner.getName() + "did something!");
  }
}
// how to use:
User user= new User();
user.setName("Chrisme");
user.doSomethinga();

you can access original class's public method via expandOwner in delegate class.