0

I have a 3 questions on overloaded constructors:

1.On the line marked line 1, I am calling an overloaded constructor but the compiler doesn't resolve the call,
is there something else I need to do?

  1. On the line marked with a 2, The compiler complains that the "this()" needs to be the first statement in the method, when it is. What's with that?

  2. If I am writing an overloaded constructor, and I haven't overridden the default constructor do I need an explicit "this();" in the overloaded constructor, if i want to execute the behavior of the default constructor, or is it included in all constructors for "free"?

.

class JavaSnippet {


public static void main(String[] args) {

          String MenuItemName="Coffee";
          double MenuItemPrice=1.0;
          Item MenuItem;
     //1-> MenuItem=new Item(MenuItemName,MenuItemPrice);// Get "cannot find symbol"
    }
}         

 class Item {
    String name;
     double price;

      public void  Item(String InName, double InPrice)   {
// 2-> this();// get "call to this must be first statement in constructor"


     name=InName;
     price=InPrice;
     }

}
2
  • maybe it is too late already but i can not see an error there. hm. never mind... nevertheless, please dont use capital letters at the beginning of reference names, it is a matter of style of course. but you will soon see it is easier to distinguish between class names and other stuff. a common way of naming style is something like: class names - capital letter at beginning, reference - small letters, constants - capital letters ... Commented Dec 12, 2010 at 22:41
  • ahhh found one - dont write "void" in front of item constructor, this should do both errors Commented Dec 12, 2010 at 22:44

2 Answers 2

3

Currently you are not defining a constructor. It should not have a return type (yours has void). So:

public Item(String InName, double InPrice) { .. }

Then, calling this() will not work again. When you define a constructor with arguments, the default (no-arg) constructor is "lost". So you can't call it. And in your case - you don't need it.

(Also note that variable names in Java should start with lower-case (by convention))

Sign up to request clarification or add additional context in comments.

Comments

2

Your Constructor has a method signature. The constructor of item should be

public Item(String InName, double InPrice) { ... } 

and not

public void Item(...)

And your second question: If you want to call the other (not overriden, but explicitely defined parameterless) constructor, you need an explicit call to this(). If you want to call a constructor from a super-class, the call is super().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.