简体   繁体   中英

How to access local variables of inner class

I have a class with a inner class of type array. I want to get access to the local variable in the inner class outside the outer class.

public class Fruits {

    public Citrus citrus[];
}
public class Citrus{

    public String lemon;
    public String orange;
}

Now I want to get the variable lemon from inner class outside of these classes. I get the error class cannot be resolved to type

Try to change public Fruits citrus[]; to public Citrus citrus[];

i find a way for u. when u use array, u should use index for access each item of array.

public class Fruits {

    public Citrus citrus[];

    public void  test() {
        String temp=citrus[0].lemon;
    }

}
 class Citrus {
    public String lemon;
    public String orange;
}

now in u can get lemons and oranges from array.

I think all you want to is accessing the inner class from outside. Below code snippet might be helpful if you just want to instantiate the inner class.

Code is self explanatory just go through comment.

public class Fruits {

    public Citrus[] Citrus;

    public class Citrus {

        public String lemon;
        public String orange;

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Citrus [lemon=");
            builder.append(lemon);
            builder.append(", orange=");
            builder.append(orange);
            builder.append("]");
            return builder.toString();
        }


    }

    public static void main(String...args)
    {

        //create the Fruits Object 
        Fruits f = new Fruits();
        //Array Declaration for inner class 
        Fruits.Citrus[] citrusArray = new Fruits.Citrus[1];
        //instanciate the inner class 
        Fruits.Citrus citrus = f.new Citrus();
        //assigning the value
        citrus.lemon = "Lemon";
        citrus.orange="Orance";

        //set instance of inner class into the array of inner class 
        citrusArray[0]=citrus;
        //setting array into the insatnce variable of Fruits class 
        f.Citrus = citrusArray;
        //printing the result
        System.out.println(Arrays.toString(f.Citrus));

    }
}

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