1

Suppose I have a constructor in c++ as:

public class Machine { 
public:
 Machine(int boltCount, bool failure=false); 
}; 

How do I convert this to an equivalent class in Java?

Thanks,

5
  • 3
    it is not valid c++. params with defaults can only be last ones Commented Nov 9, 2010 at 20:28
  • Really? Besides the obvious problem pointed out by Andrey, it is simply a class declaration and a constructor. Java does not support default argument values, so you will have to use constructor chaining. Commented Nov 9, 2010 at 20:30
  • 1
    This is not valid C++: there are no public classes, and the parameters with default values must be rightmost. So it's not clear what it actually is that you want an equivalent for. Commented Nov 9, 2010 at 20:30
  • "public class XXX" is valid C++?? When did that happen? Commented Nov 9, 2010 at 20:30
  • @Noah: When Sun bought MicroSoft and took over the world. Commented Nov 9, 2010 at 20:42

2 Answers 2

7

something like that

public class Machine { 
   public Machine(int boltCount) { this(boltCount, false); }
   public Machine(int boltCount, bool failure) { /*body here*/ }
}; 
Sign up to request clarification or add additional context in comments.

3 Comments

Ahh! Got it.. There is a constructor explosion but I think this works.. Thanks!
i want to add that C# 4.0 has optional parameters! (trying to make java developers switch to c# :)
I mean for each c++ constructor with one default value set, this gives rise to 2x Java constructors.
2

You would have to use constructor chaining, as Java does not have default values for parameters:

public class Machine {
    Machine(int boltCount) {
        this(boltCount, false);
    }

    Machine(int boltCount, boolean failure) {
        // constructor logic
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.