-2

I have the following code:

public class A
{
    private class B
    {
        public String a = "";
        public B(String a)
        {
          System.out.println("hello");
          this.a = a;
        }
    }

    public A()
    {
        System.out.println("bla");
        B b = new B("what's up?");
        System.out.println("world");
    }

    public static void main(String[] args)
    {
       new A();
    }
}

For some reason, only the "bla" is printed, the other prints aren't printed. I'm loading this class file with jni using dynamic class loading and calling the main function.

What am I doing wrong?

John Doe
  • 169
  • 1
  • 8

1 Answers1

1

there you go, this code works:

public class A
{
    static class B
    {
        public String a = "";
        public B(String a)
        {
          System.out.println("hello");
          this.a = a;
        }
    }

    public A()
    {
        System.out.println("bla");
        B b = new B("what's up?");
        System.out.println("world");
    }

    public static void main(String[] args)
    {
       new A();
       A.B myAB = new A.B("hello");
    }
}

OUTPUT:

bla
hello
world
hello

if you want to print in class B the actual string "a", then change public String a = ""; to System.out.println(a); in which case you will get

bla
what's up?
world
hello

since "what's up?" is passed to class B

See the Javadocs for nested classes, it will help you a lot I think: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

adrCoder
  • 3,145
  • 4
  • 31
  • 56