1

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();
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • No you can’t, by definition an inner class needs an instance of an outer class and creating an instance always invokes the constructor. [barring esoteric cases like deserialization and cloning] – Erwin Bolwidt Sep 07 '18 at 09:42
  • An inner class is part of the instance, a static nested class is just part of the class. This is the same as a member, you can't access a variable without creating an instance first. – AxelH Sep 07 '18 at 09:45
  • 1
    Possible duplicate of [Java inner class and static nested class](https://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class) – AxelH Sep 07 '18 at 09:46

2 Answers2

4

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

Eugene
  • 117,005
  • 15
  • 201
  • 306
0
    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
Ram Chhabra
  • 421
  • 8
  • 11