This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
I have a question regarding nested class. Below is from one of the Review Questions from "A programmers guide to Java" Chapter 7 7.7 Page 248. Which of these statements are true? Select all valid answers (a) You cannot declare static members within a non-static inner class. (b) If a non-static inner class is nested within a class named Outer, then methods within the non-static inner class must use the prefix Outer.this to access the members of the class Outer. (c) All member variables in any nested class must be declared final. (d) Anonymous classes cannot have constructors. (e) If objRef is an instance of any nested class within the class Outer, then (objRef instanceof outer) would yield true. Why is (b) not true?
A non-static inner class can not have static members. But it helps to know WHY, otherwise if you're like me, you'll likely forget. I'm still in training for the SCJP myself, so correct me if I'm wrong, but I believe the reason is that since the inner class is non-static, the inner class does not exist unless there is an instance of the outer class first. So you can't just do: Outer.Inner.staticVar = 123; Now, think about static inner classes, or as they call them "top-level nested inner classes". Why else would we be able to use static? We obviously can't use static for regular top-level classes, but we can for inner classes. Here you put the keyword "static" as part of the inner class delcaration. Now you are allowed to declare static members in the inner class because the inner class is static and has existence on it's own without the need for an instance of the outer class to exist, sort of like static member variables.
Hope this helped more than it confused. If you can grasp certain concepts, then in some cases like this you can figure it out without memorization.
I was doing some studying today, and I thought in one of Dan Chisolm's mock exams he said you could have static members in non-static inner classes as long as they were compile time constants - like: static final int x = 2; ???
I was doing some studying today, and I thought in one of Dan Chisolm's mock exams he said you could have static members in non-static inner classes as long as they were compile time constants - like: static final int x = 2;
i think in this example it is valid because that static is used together with final, which makes x to be a constant. if you try put something like "static int x = 2;" in a non-static inner class, you are bonded to have a compiler error.....
The reason b is wrong is because of the word "must". In your example you had to use it becuse you had a variable called one in the inner class. If you didn't then there would have been no need to use the Outer.this form.