简体   繁体   中英

Creating new object in java error

I wrote this code in the main:

if (startAmount>0) //create new cashier object with or without a start amount
    Cashier newCashier = new Cashier(startAmount);
else Cashier newCashier = new Cashier();

and got an compile error for the second and third lines:

Multiple markers at this line
    - Cashier cannot be resolved to a variable
    - Syntax error on token "newCashier", delete

and:

Multiple markers at this line
    - Cashier cannot be resolved to a variable
    - Syntax error, insert "AssignmentOperator Expression" to complete 
     Assignment
    - Syntax error, insert ";" to complete Statement

but when i write the code like this with brackets:

if (startAmount>0)//create new cashier object with or without a start amount
{
    Cashier newCashier = new Cashier(startAmount);
}
else{ Cashier newCashier = new Cashier();}

it seems to be okay, no compile errors. can someone help me understand why?

Why are you creating shadow variable for newCachier reference, you could rather do this

Cashier newCashier = null;
if (startAmount>0) //create new cashier object with or without a start amount
    newCashier = new Cashier(startAmount);
else 
     newCashier = new Cashier();

It's always better to add those curly braces. Cause you won't forget to add them when you extend your code, which leads to strange behavior otherwise.

I think your exception of the first might came cause you forgot to put your else statement in a new line, but I am not sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM