java / devjava-content

55 stars 16 forks source link

nested class can get static member #105

Open Just-some-one opened 4 months ago

Just-some-one commented 4 months ago

in inner class part

it said

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

that not the case now we can define static members inside inner class not sure which jdk introduced that but at least since jdk 17

and for local class

Local classes are similar to inner classes because they cannot define or declare any static members.

that not the case now we can define static members inside local class

You cannot declare an interface inside a block; interfaces are inherently static. For example, the following code excerpt does not compile because the interface HelloThere is defined inside the body of the method greetInEnglish():

the code will compile the only issue that name is not defined

public void greetInEnglish() {
    interface HelloThere {
       public void greet();
    }
    class EnglishHelloThere implements HelloThere {
        public void greet() {
            System.out.println("Hello " + name);   // name not defined replacing it with any string literal will make the code work
        }
    }
    HelloThere myGreeting = new EnglishHelloThere();
    myGreeting.greet();
}

and also

You cannot declare static initializers or member interfaces in a local class. The following code excerpt does not compile because the method EnglishGoodbye.sayGoodbye() is declared static. The compiler generates an error similar to "modifier static is only allowed in constant variable declaration" when it encounters this method definition:

the code will work also

for accessing-local-variables-of-the-enclosing-scope-and-declaring-and-accessing-members-of-the-anonymous-class

You cannot declare static initializers or member interfaces in an anonymous class.

again now we can do that

i see it a copy from the old java tutorial that why it stick with jdk 8

another point not sure if it would be better to change the order of the nested class after the intro to interface as anonymous class depend on it also other example on the page use inheritance or we keep it and use the same concept of take it for grant till you learn more same when we write our first hello world we do not know what system or out do

thanks for your time and have a nice day :)