Ken Lange
Ken Lange

Reputation: 963

overloading constructors

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;
     }

}

Upvotes: 0

Views: 130

Answers (2)

Matten
Matten

Reputation: 17631

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().

Upvotes: 2

Bozho
Bozho

Reputation: 597046

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))

Upvotes: 3

Related Questions