-2

I have MyClass mc=new MyClass();, I need an access to subclass: mc.Sub.Check().

https://stackoverflow.com/a/488749/1234275 - doesn't work in this case.

public class MyClass {
  public onCreate() {
    super();
  }
  Public class Sub {
    public void Check() {
      //
    }
  }
}
Community
  • 1
  • 1
anony_root
  • 1,477
  • 4
  • 16
  • 25
  • You have an inner class. The link does not. – keyser May 14 '12 at 08:26
  • What I'm saying is that it's not a related question. – keyser May 14 '12 at 08:30
  • 5
    Read up a little on java. First of all, `Public class Sub` should be `public class Sub`, secondly you are calling your super constructor from `onCreate()` you most likely want to call `super.onCreate()` if `MyClass` is an extension of `Activity`, although you are missing the `extends Activity` part. Third, if you want to access a method from a subclass like your example (without instantiation) you have to make the method static. Otherwise you would call `new MyClass.Sub().Check()`. And finally it is recommended that you follow the java naming convention and rename `Check()` `check()` – Jave May 14 '12 at 08:32
  • @Jave you're not right in a few things. It isn't an extension of Activity & I didn't miss it. I don't actually need static class, because I use this class only in one part of app. But anyway I thumbed up your comment. :) – anony_root May 14 '12 at 08:37
  • @Jave also I solved it in this way: MyClass.Sub sub=new MyClass.Sub(); – anony_root May 14 '12 at 08:38

3 Answers3

0

You can initiate the inner class like any other class, i.e. new MyClass.Sub, then call the method. If you want to skip initiation you have to declare the nested class as static.

(Also: an instance of a non-static inner class can only exist in the context of an instance of the containing class).

keyser
  • 18,829
  • 16
  • 59
  • 101
0

You just have to create the Object of the Inner class like normal class. In above case you can do by following.

Sub sub = new Sub();

sub.check();

put above code Inside the onCreate();

Hope this will help you.

mayur rahatekar
  • 4,410
  • 12
  • 37
  • 51
  • Solved: MyClass.Sub a=new MyClass.Sub();. I don't actually need it in onCreate(), because MyClass is big & I seldom use Sub. But it works too, accept. – anony_root May 14 '12 at 08:34
0

Only Static Methods are called with class name, either you make the method static or create an instance of inner class in outer class and all the method with the instance.

Animesh Sinha
  • 1,045
  • 9
  • 16