Is it a bad practice to have multiple classes in the same file?

I used to have one class for one file. For example car.cs has the class car. But as I program more classes, I would like to add them to the same file. For example car.cs has the class car and the door class, etc.

My question is good for Java, C#, PHP or any other programming language. Should I try not having multiple classes in the same file or is it ok?


I think you should try to keep your code to 1 class per file.

I suggest this because it will be easier to find your class later. Also, it will work better with your source control system (if a file changes, then you know that a particular class has changed).

The only time I think it's correct to use more than one class per file is when you are using internal classes... but internal classes are inside another class, and thus can be left inside the same file. The inner classes roles are strongly related to the outer classes, so placing them in the same file is fine.


In Java, one public class per file is the way the language works. A group of Java files can be collected into a package.

In Python, however, files are "modules", and typically have a number of closely related classes. A Python package is a directory, just like a Java package.

This gives Python an extra level of grouping between class and package.

There is no one right answer that is language-agnostic. It varies with the language.