0

I am studying inner classes in Java.There is an example of using inner classes with different access modifiers.I wrote the code just I see in the book but I get an error which I have mentioned at the title.As I know we cant use a static variable,method in a non-static scope but what I dont understand is I get this error only with my String array.Integer array works fine.What am I missing here?

package innerclasses;

public class AlanlaraErisim {

private class StringDiziYaz{

    private void diziYaz(String[]dizi){

        for(String x: dizi){

            System.out.println(x + " ");

        }

    }

}


protected class IntegerDiziYaz{

    protected void diziYaz(Integer[]dizi){

        for(Integer x: dizi){

            System.out.println(x + " ");

        }

    }

}



public static void main(String[] args) {

    AlanlaraErisim.StringDiziYaz stringDiziYaz = new AlanlaraErisim().new StringDiziYaz();

    String[] stringDizi = {"abc","def","ghi","jkl","mno"};
    StringDiziYaz.diziYaz(stringDizi);  //Gives the error

    AlanlaraErisim.IntegerDiziYaz integerDiziYaz = new AlanlaraErisim().new IntegerDiziYaz();

    Integer[] intDizi = {1,2,3,4,5,6};  
    integerDiziYaz.diziYaz(intDizi); //Works fine

}}

Thats the output:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - non-static method diziYaz(java.lang.String[]) cannot be referenced from a static context at innerclasses.AlanlaraErisim.main(AlanlaraErisim.java:42) /Users/sametsahin/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1 BUILD FAILED (total time: 1 second)

SametSahin
  • 571
  • 3
  • 7
  • 24

1 Answers1

0

The error tells you that diziYaz() is an object method (non-static), so you cannot reference it from the class (StringDiziYaz). You must access it using an object of type StringDiziYaz.

If you change

StringDiziYaz.diziYaz(stringDizi);

to

stringDiziYaz.diziYaz(stringDizi); // capitalization of stringDiziYaz changed

then there should be no error. Perhaps you simply made a typo?

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94