Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Meet Objects Creating Classes

Anas Rida
Anas Rida
8,183 Points

creating a class in a different file

Hello,

why did we need to make a new file to create the PezDispenser class? can we create classes within the same file as out program?

thanks in advance

2 Answers

It is to promote very basic understanding or correct programming. It follows the concept of single responsibility principle. Each class should define a single responsibility that it promotes. So while Example.java is used as a starting point of the program, the core working principle is embedded into PezDispender.java file.

Yes you could by principle have both the classes in the same file, but imagine having 20 different classes in the same file. Its always better to get into the correct habit right away

Hope that helps.

Cindy Lea
PLUS
Cindy Lea
Courses Plus Student 6,497 Points

My guess is that they create separate files so its easier to find & identify the classes. If you group them in a file, the filenames might become too cumbersome. Classes are supposed to be independent objects.