i want to access the arr variable from inside the inner class method MyMethod. When i try to print it from there i end up getting a null pointer exception.
public class MyClass{
String[] arr;
MyClass my;
public MyClass(){
my = new MyClass();
}
public class MyInner {
public void MyMethod() {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main(String[] args) {
String[] n={"ddd","f"};
my.arr=n;
}
}
You can use just arr. However until you set it to something it will be null
BTW: Your my = new MyClass() will blow up as it will create objects until it stack overflows.
You haven't initialized it yet, so the reference is null. Initialize it in your constructor for example, and you will have access to the variable via your inner class.
public class MyClass {
String[] arr;
public MyClass (String[] a_arr) {
arr = a_arr;
}
public class MyInner {
public void MyMethod () {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main (String[] args) {
String[] n= {"ddd","f"};
MyClass myClass = new MyClass (n);
}
}
Well, for starters in your main method you never create an instance of your class.
Also, MyClass has a reference to a MyClass object. In the constructor of MyClass, it initializes that reference by calling it's own constructor. That's an endless loop.
Do the following. Your way of initialization is wrong.
public class MyClass{
String[] arr;
MyClass my;
public MyClass(){
}
public class MyInner {
public void MyMethod() {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main(String[] args) {
String[] n={"ddd","f"};
MyClass my=new MyClass();
String[] b = new String[2];
System.arraycopy( n, 0, b, 0, n.length );
}
}
In case of more than 2 strings, simply do String[] b = new String[n.length];
Related
This is my code:
public class MyClass {
int x;
MyClass m1 = new MyClass();
m1.x=10;
}
Why does line m1.x=10; result in error?
if you want to assign value to the variable x,
the line initializes it should be placed in specific method like below.
did you intend to do this?
public class MyClass
{
int x;
public static void main(String[] args)
{
MyClass m1 = new MyClass();
m1.x = 10;
}
}
Use instance initialization block:
public class MyClass {
int x; // define x variable
MyClass m1 = new MyClass(); // initialize m1 variable
{
m1.x=10; // assign 10 to m1.x (this is assignment statement)
}
}
Out of block you can do only defining and initializing variables, not assignment statement.
There are two errors in your code:
MyClass m1 = new MyClass();
This is an infinite recursion.
m1.x=10;
This is a statement, and as such should be within a method or constructor, not the class body.
The problem here is the code m1.x=10;
This line shows an operation or behavior which is only permissible within a block of code.
Valid Code for this operation.
public class MyClass {
int x;
public void assignOperation() {
this.x = 10;
}
public static void main( String[] args ) {
MyClass myClass = new MyClass();
myClass.assignOperation();
System.out.println( "Assigned value is " + this.x )
}
}
Another valid example outside of a method but within the class body will be :
public class MyClass {
static int x;
static {
x = 10;
}
public static void main( String[] args ) {
System.out.println( "Assigned value is " + x )
}
}
making variable x static doesn't need us initialize an object of the class MyClass.
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?
ClassOuter.DataInner value = outerObj.new ClassOuter.DataInner();
This syntax applies to inner classes (i.e. non static nested classes). If that's what you want, remove the static keyword from public static class DataInner.
EDIT :
Also change
ClassOuter.DataInner value = outerObj.new ClassOuter.DataInner();
to
ClassOuter.DataInner value = outerObj.new DataInner();
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's getNo() method, since outerObj and value 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 :
public class Main {
public static void main( String[] args ) {
...
ClassOuter outerObj = new ClassOuter();
ClassOuter.DataInner value = outerObj.new DataInner();
outerObj.setInner (value);
}
}
class ClassOuter{
public static class DataInner{
public int x;
}
...
private DataInner inner = null;
public void setInner (DataInner inner) {
this.inner = inner;
}
protected void getNo()
{
inner.x=Integer.parseInt("493");
}
}
If DataInner must be static class:
public class Main {
public static void main(String[] args) {
ClassOuter outerObj = new ClassOuter();
ClassOuter.DataInner value = new ClassOuter.DataInner();
}
}
class ClassOuter {
public static class DataInner {
public int value;
}
}
It this case, DataInner has no reference to the ClassOuter instance.
If DataInner must not be static class.
public class Main {
public static void main(String[] args) {
ClassOuter outerObj = new ClassOuter();
ClassOuter.DataInner value = outerObj.newInner();
}
}
class ClassOuter {
public class DataInner {
public int value;
}
public DataInner newInner() {
return new DataInner();
}
In this case, DataInner has reference to the ClassOuter instance (ClassOuter.this).
Is it possible to have a "global" variable, i.e., "balance", which all methods can access without parameters?
Something like:
public static void main(String[] args{
makevariablehere
}
Could be called in another method:
public static int someMethod() {
variable = newVariable;
}
You can define it as a static field on the class. See the example below, which stores the number of args passed to the main method in a static field, so that it may be returned by the getNumberOfArgs() method.
public class MyClass {
private static int argCount;
public static void main(String[] args) {
argCount = args.length;
}
public static int getNumberOfArgs() {
return argCount;
}
}
I have something similar to:
public class A{
public static B[] bObj;
public A(){
bObj = new B[2]; // create array of objects of class B
}
public static void main(String[] args){
A aObj = new A();
for(i=0;i<2;i++){
bObj[i].testprint();
}
}
}
class B{
public testprint(){
System.out.println("Inside testprint()");
}
}
When I run this, I get NullPointer exception at bObj[i].testprint(). I did do new B() in the constructor of A. But I don't know why it isn't working.
Understand that initializing an array of reference, doesn't really initializes the references inside it. They are still null. You need to initialize them by iterating over the array.
public A(){
bObj = new B[2];
for (int i = 0; i < bObj.length; ++i) { bObj[i] = new B(); }
}
I want to create an object using a method but I want it (object+reference) to live even after the method ends. Example of code:
public class start{
public static void main (String [] Args){
public void createObject(){
object1 createdObject = new object1();
}
createObject();
createdObject.doSomething();
}
}
public class object1{
//code for object 1
}
So my main question is: how to create object using method and let it live even after method ends. The problem is that reference createdObject is popped of stack after method ends and therefore I can't use it anymore. Is it even possible to create object for further use this way?
public class start{
public static void main (String [] Args){
//class level scope
object1 createdObject = null;
private void createObject(){
createdObject = new object1();
}
}
public class object1{
//code for object 1
}
NOTE: I have not following naming conventions. But please follow them in actual code
UPDATE: Proper code check it out
public class Main {
public static void main(String[] args) {
new MyClass().doSomething();
}
}
class MyClass{
Object obj ;
public void doSomething(){
createObject();
}
private void createObject(){
obj = new Object();
System.out.println("Created MyClass instance");
}
}
Your method should return object1 instead of void and you have to add the following line at the end of the method:
return createdObject;