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 Meet Objects Add a Constructor

Roque Sosa
PLUS
Roque Sosa
Courses Plus Student 1,024 Points

Class variables - declaration vs contructor

If I set a private variable on a class to a value 'x', and then the constructor asks for a value to change it. Is it mandatoyry for me to erase the 'x' value , or, can I let 'x' as a default value in case I dont enter a value for the contractor.

Example:

Class Test{ private String variable = "Text";

public Test(String variable){ this.variable = variable; } }

//with constructor

Test testing1 = new Test(textTesting1);

testing1.variable=textTesting1 // True

//without constructor

Test testing2 = new Test()

testing2.variable=Text // Is this true??

1 Answer

andren
andren
28,558 Points

It's not mandatory erase the value, but it would not work with the way you have it setup.

The issue is that in Java parameters are not optional, if you declare a method/constructor with one then an argument has to be supplied when the method/constructor in question is called. Since the constructor has a string parameter defined you need to supply a string argument to call it. If you don't then Java would complain that it couldn't find a constructor that does not take any arguments.

You can get around this by actually creating a second constructor which does not take any arguments. Like this:

public class Test { 
    private String variable = "Text";

    public Test(){ // This constructor gets called if no argument is supplied
    }

    public Test(String variable){ // This constructor gets called if a string argument is supplied
        this.variable = variable; 
    } 
}

This is an example of method overloading, which is the practice of having multiple methods/constructors named the same thing that takes different arguments.