Link to home
Start Free TrialLog in
Avatar of techbro
techbroFlag for United States of America

asked on

Inner Class in Java

I want the output "hi" by print statement.
In line 6, if I use "drive()" or "Car.this.drive()", I get the desired output.
I like to know why it causes compiler error if I use "Car.drive()" or "this.drive()" in line 6 to print the output.

public class Car
{
	class Engine
	{
		{
			drive();
		}
	}
	
	public static void main(String [] args)
	{
		new Car().go();
	}
	
	void go()
	{
		new Engine();
	}
	
	void drive()
	{
		System.out.println("hi");
	}
}

Open in new window

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

>>I like to know why it causes compiler error if I use "Car.drive()" or "this.drive()" in line 6 to print the output.

Because there's no enclosing instance of Car

Oops - ignore that sorry
Car.drive() is to call a static method in Car class. there is not one
this.drive() is to call a drive method in the Engine class which again does not exist
Car.this.drive() on the other hand says to call the drive() method in the outer class named Car, which does exist
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of techbro

ASKER

Appreciate your response.
Could you please explain what you mean by "drive() is not a static method of class Car"?

It's not declared as static

static void drive() ............
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of techbro

ASKER

When I am instantiating the class Car, it seems to work fine even if the "drive" method is not static.
I am sorry for the confusion, but why the "drive" needs to be static if I use Car.drive()?

class Engine
{
	{
		Car d = new Car();
		d.drive();
	}
}

Open in new window

d.drive()

is not the same as

Car.drive()
>>but why the "drive" needs to be static if I use Car.drive()?

Because that's the form for calling a static method - which is also called a 'class method' (which should help you to understand whay)
Avatar of techbro

ASKER

Thank you for your help!
The accepted comment just copies what I had already posted at 35184802
why did you accept it and not mine?
Avatar of techbro

ASKER

I was only focusing on giving points to the participants that I was not aware of the comments. Sorry about that!