File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Glen Iris
Ranch Hand
Posts: 168
Chrome Java Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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()"?



 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Glen Iris
Ranch Hand
Posts: 168
Chrome Java Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Anayonkar Shivalkar. Your explaination is very clear and i now understand the solutions. :-)
 
prashant modak
Greenhorn
Posts: 14
Java Linux Redhat
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..........
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic