techbro
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.
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");
}
}
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Appreciate your response.
Could you please explain what you mean by "drive() is not a static method of class Car"?
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() ............
static void drive() ............
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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()?
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();
}
}
d.drive()
is not the same as
Car.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)
Because that's the form for calling a static method - which is also called a 'class method' (which should help you to understand whay)
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?
why did you accept it and not mine?
ASKER
I was only focusing on giving points to the participants that I was not aware of the comments. Sorry about that!
Because there's no enclosing instance of Car