Reputation: 35
Can you call method in inner class without calling constructor in class A
this my code:
public class A {
public A() {
System.out.println("You are in Class A");
}
public class innerA {
public innerA() {
System.out.println("You Are in Class InnerA");
}
public void PrintName() {
System.out.println("Jack in InnerA");
}
}
}
public class B {
A.innerA obj = new A().new innerA();
}
Upvotes: 1
Views: 2418
Reputation: 441
class Car {
void carMethod() {
System.out.println("inside carMethod");
class TataCar {
void tataCarMethod() {
System.out.println("inside tataCarMethod");
}
}
TataCar y = new TataCar();
y.tataCarMethod();
}
}
class MainClass {
public static void main(String[] args) {
Car carObj=new Car();
carObj.carMethod();
}
}
Output:
inside carMethod
inside tataCarMethod
Upvotes: 0
Reputation: 120858
Well you need an instance of InnerA
to actually call a method on it and in your case you can't do that because you would also need an instance of A
for that.
You could change the declaration to:
static public class InnerA {...}
thus not needing an instance of A
, only an instance of InnerA
Upvotes: 4