aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inner Classes and the word 'this'- Chapter 8 Question 9 page 697 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Inner Classes and the word Watch "Inner Classes and the word New topic
Author

Inner Classes and the word 'this'- Chapter 8 Question 9 page 697

Glen Iris
Ranch Hand

Joined: Jul 13, 2011
Posts: 164



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, OCMJD
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1509
    
    5

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, OCEEJBD)
Glen Iris
Ranch Hand

Joined: Jul 13, 2011
Posts: 164

Thank you Anayonkar Shivalkar. Your explaination is very clear and i now understand the solutions. :-)
prashant modak
Greenhorn

Joined: Nov 05, 2011
Posts: 13

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inner Classes and the word 'this'- Chapter 8 Question 9 page 697