简体   繁体   中英

Can Methods in OuterClass can invoke only static methods in the static InnerClass?

This was a question i got recently - multi choice, but im struggling to see why 5 is not part of the answer.. The correct answer is (2,4) but i picked (2,4,5)...

1) Methods in InnerClass have a direct access to all the fields of OuterClass

2) Methods in InnerClass have a direct access to the static fields of OuterClass

3) Methods in InnerClass can invoke any method in the OuterClass

4) Methods in InnerClass can invoke only static methods in the OuterClass

5) Methods in OuterClass can invoke only static methods in the InnerClass

public class OuterClass {
      private int value;
      private static class InnerClass {
        // inner class methods
      }
      // outer class methods
    }

It depends on how you interpret it. The code InnerClass.nonStaticMethod() won't work, since you need to create an instance of the class. If this is meant, 5 would be correct. But it looks like the question meant if this code was possible: innerClassInstance.nonStaticMethod() In this case 5 is wrong since every class can call a public non-static method through an instance of the class.

maybe this is much more accurate to see that 5 is wrong

public class OuterClass 
{
  private int value;
  private static String s2="outterString_2";
  public String s3="outterString_3";
  private String msg = "to be set";
  private String getMsg()
  {
      return msg;
  }
  public static void main(String args[])
  {
      System.out.println(new OuterClass.InnerClass().out("non_static_Inner method access from Outers"));
      System.out.println(new OuterClass.InnerClass().out2());
      System.out.println(new OuterClass.InnerClass().out3());
      OuterClass o = new OuterClass();
      InnerClass i = new OuterClass.InnerClass(o);
      o.msg="new Message";        
      System.out.println(i.o.getMsg());


  }
  private static class InnerClass
  {
    public OuterClass o=null;  
    InnerClass()
    {

    }
    InnerClass(OuterClass o)
    {
        this.o = o;
    }
    public String out(String s)
    {
        return s;
    }
    public String out2()
    {
        return OuterClass.s2;
    }
    public String out3()
    {
        return new OuterClass().s3;
    }
  }
}

Output
non_static_Inner method accessed from Outers
outterString_2
outterString_3
new Message - set before on o_instance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM