Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an inner class without putting the definition of inner class to parent class?

I'll write an header file,and it's very long.Since it will be too complicated,i don't want to put inner class definition in root class.I mean how can i make a class inner without writing it in root class.

class outer
{

}

class inner
{

}

If i can use like that, The header file will be clearer i think.

like image 310
Viplime Avatar asked Jan 01 '12 14:01

Viplime


People also ask

How do you create an inner class instance from outside the outer class instance code?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.

Can you create an inner class inside a method?

Method-local Inner Class In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined.

Can we define inner class inside final class?

No, it's not similar to constant variable. It means that you can't create a sub-class of this nested class ( Inner ). This is similar to using the final keyword in top level (i.e. not nested) classes.

Can I create a class inside a class?

In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and creates more readable and maintainable code.


2 Answers

Like this:

// foo.hpp

class Foo
{
public:
  class Inner;
  Foo();
  void bar();
  Inner zoo();
};

// foo_inner.hpp

#include "foo.hpp"

class Foo::Inner
{
  void func();
};

Then, in the implementation:

#include "foo.hpp"
#include "foo_inner.hpp"

void Foo::bar() { /* ... */ }
void Foo::Inner::func() { /* ... */ }

Note that you can use the incomplete type Foo::Inner inside the class definition of Foo (i.e. in foo.hpp) subject to the usual restrictions for incomplete types, e.g. Inner may appear as a function return type, function argument, reference, or pointer. As long as the member function implementations for the class Foo can see the class definition of Foo::Inner (by including foo_inner.hpp), all is well.

like image 179
Kerrek SB Avatar answered Nov 15 '22 05:11

Kerrek SB


You can specify 'outer' as "public class outer", and put both its definition and the "inner" definition into a "class.java" file, and code in outer can instantiate inner just as if inner was in a different source file. It is not clear that is what you're after, because you have not explained why you want an "inner" class.

like image 27
arcy Avatar answered Nov 15 '22 04:11

arcy