I am used to code in C++, but have to convert a project from C++ to Java. In C++ using data structure is pretty much simple. I am trying to replicate the same thing, but such as a Java inner class and static nested class. After reading several examples online, and trying different versions, so far this is what I got:
public class Main {
public static void main( String[] args ) {
...
ClassOuter outerObj = new ClassOuter();
ClassOuter.DataInner value = outerObj.new ClassOuter.DataInner();
}
}
class ClassOuter{
public static class DataInner{
public int x;
}
...
protected void getNo()
{ value.x=Integer.parseInt("493");
}
}
However, when I try to compile, it gives me the error:
$ javac -cp "./" Main.java
Main.java:15: error: '(' expected
ClassOuter.DataInner value = outerObj.new ClassOuter.DataInner();
Any clue about what is missing here?
This syntax applies to inner classes (i.e. non static nested classes). If that's what you want, remove the
static
keyword frompublic static class DataInner
.EDIT :
Also change
to
You don't specify the outer type when using an enclosing instance to initialize the inner instance.
And the line
outerObj.value.x=Integer.parseInt("493");
is not valid inside your outer class'sgetNo()
method, sinceouterObj
andvalue
are local variables known only to your main method.If you wish your outer instance to update any of its inner instances, it must obtain a reference to it. Here's one way to do it :