Rasul Patrick wrote:
1. How the above statement is grammatically correct ?
What do you think is wrong with it?
How it is working ?
Do you understand how this code works?
It's the same thing, except we're not storing a reference to the Rectangle object in a variable. The expression
new Rectangle() is of the type "reference to Rectangle". The expression
rect is also of the type "reference to Rectangle." When we say
height = <SOMETHING>.height all that matters is that
<SOMETHING> is of the type "reference to Rectangle". It doesn't matter if
<SOMETHING> is a variable name or the result of the
new operator or the result of a method call, such as
int height = getSomeRectangle().height;
(And actually, it doesn't even have to be Rectangle. It just has to be some type that has an accessible
height field.)
2. What does it mean by 'default height' (means the purpose of this code) ?
It means the height of a newly created Rectangle if we don't specify the height explicitly as a constructor parameter and haven't set it after construction.
The purpose of this particular code is to demonstrate how you can use this kind of construct and what its results are. The purpose of this kind of code in general is to be lazy and not create an extra variable when you don't need one. Some people will say that's bad practice. I kind of agree with them, but I do it myself occasionally too.