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

Is there a way to initialize an object without a constructor?

So in java when initializing a String you don't need to make use of a constructor, you just put in the literal but you can use the constructor if you please since String is a class. Now my question is is there any way to initialize a user-made class without the constructor?

1 Answer

Tonnie Fanadez
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 Points

Ibrahim Adeosun I will try to answer your question as best as I can.

A String is a sequence of characters and all string literals such as "abcd" or "Ibrahim" etc are implemented as instances of the String class. You can use the same pattern with other primitive data types like int, double or boolean

  String name = "Ibrahim Adeosun";
  int number = 17;
  double aDouble = 20.153;
  boolean notTrue = false;

But there is one thing to note - int is a Primitive Data Type - these store the value, for example the above int number stores 17 as a value. String class is a Reference Data Type meaning String Class stores a reference to the object rather than the object itself. In other words String Class and other Reference Types(User-Made Classes) don't store the value, but store a reference to that value or an address to a value.

Back to your question on User-Made Classes. Let's take an example of a Person Class -with 2 properties i.e. name and age. The Person class has an empty constructor(default constructor of which you don't have to write)

public class Person {

  public String name;
  public int age;
//default constructor
  public Person() {}

}

To make instances of Person Class you will need to instantiate class Person you need to use the new keyword, the class Name followed by the empty constructor.

Person firstPerson = new Person();
Person secondPerson = new Person();
Person thirdPerson = new Person();

So to answer your original question - when it comes to Reference Types/User-Made Classes you have to use a constructor during instantiation. In fact, the chief precise function of Constructors in Object-Oriented Programming is to initialize objects!!!