| Author |
Inner Classes and the word 'this'- Chapter 8 Question 9 page 697
|
Glen Iris
Ranch Hand
Joined: Jul 13, 2011
Posts: 69
|
|
Hello once again friends.
I understand that to reference the outer class from within an inner class the syntax is OuterClassName.this and therefore I can see that if were placed on line 3 that the output would be "hi".
However, I am still confused about two things -
1 - I cannot understand why Car.this.drive(); needs to be wrapped in chain brackets, ie
2 - Placing the code will produce the same output (hi). How is this so? Is this line of code effectivley saying to the JVM - "Regarding your Engine instance, call Car.this.drive()"?
|
OCPJP 6
|
 |
Anayonkar Shivalkar
Ranch Hand
Joined: Dec 08, 2010
Posts: 673
|
|
Glen Iris wrote: 1 - I cannot understand why Car.this.drive(); needs to be wrapped in chain brackets
That is because, method invocation is not allowed inside a class and outside any method and any initializing block.
When we say then we put method call to drive inside initialization block, hence it works.
Glen Iris wrote: 2 - Placing the code
will produce the same output (hi). How is this so?
Well, that is because, the call to drive method was simply removed from initializer block and added to default constructor of Engine. When go method creates a new object of Engine, drive method is invoked.
I hope this helps.
|
Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD)
|
 |
Glen Iris
Ranch Hand
Joined: Jul 13, 2011
Posts: 69
|
|
|
Thank you Anayonkar Shivalkar. Your explaination is very clear and i now understand the solutions. :-)
|
 |
prashant modak
Greenhorn
Joined: Nov 05, 2011
Posts: 12
|
|
when you compile the code:
class A
{
System.out.println("hello");
}
class B
{
public static void main(String [] args)
{
A a=new A();
}
}
You will get an error.......
But if you put System.out.println("hello"); inside parenthesis you wont get any error......
cause when you put that statement inside parenthesis then it become an init block...which get loaded in stack
when we instantiate A.
so Parenthesis are required..........
|
OCJP 1.6 Certified (75%)
|
 |
 |
|
|
subject: Inner Classes and the word 'this'- Chapter 8 Question 9 page 697
|
|
|