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 Question: Object Instantiation

Could/Should you ever create an object within the constructor or method of another class? Or should the creation of objects only occur within the main() method of the main executable file?

1 Answer

Hi Bryan

It's definitely possible to create an object in a method of a class. An example can be if you have a button in your program, that when pressed should perform some sort of action that requires the creation of an object. For example if you have program with a list of students and the option to create a new student. The create button would then call a createNewStudent method that takes the information from your textfields and uses it to create a new student object.

Hope that answer is somewhat helpful :-)

Thank you, Marina. This was extremely helpful! I am still a beginner, so I am sure that was a dumb question :D