r/javahelp • • Sep 06 '15

I need help

For my assignment I need to do this....DECLARE AN INSTANCE VARIABLE CALLED NAME THAT CAN CONTAIN A VALUE SUCH AS "EGGS"....I have no idea where to start. If someone could help me get started hopefully I can finish the assignment. Thanks everyone

0 Upvotes

16 comments sorted by

View all comments

Show parent comments

1

u/yodawg32 Sep 06 '15

Okay so can't any method do this? What is the difference between a constructor and any normal method doing it?

1

u/desrtfx Out of Coffee error - System halted Sep 06 '15

The constructor performs some additional functions behind the scenes that initialize the object itself.

Constructors are called as soon as you use the new keyword.

You can use "normal" methods after the object is initialized by the constructor.

1

u/yodawg32 Sep 06 '15

So,you're saying the actual (this) variables get turned into Objects? I understand the new keyword and how you pass arguments into it so it matches the constructor. What is the significance of turning those variables into Objects? You can still use the variables fully without initialising them right?

1

u/desrtfx Out of Coffee error - System halted Sep 06 '15

Yes, you can say that this represents the current instance of the class, i.e. the current object

There can only be one this per class as it refers to the object itself.

You are not turning the variables inside the class into objects. These variables already belong to the object and are properties of the object that describe it.

You can still use the variables fully without initialising them right?

Depends: primitive types (boolean, byte, char, int, short, long, double, float) always are initialized by default (numeric types to 0, boolean to false). Object types (like String) must be initialized otherwise they contain null which will lead to NullPointerExceptions.