Anonymous inner class at member level - java

In the book 'Java OCP 8 Programmer II Study Guide', it is said that
an anonymous inner class is a local inner class
and
a local inner class is a nested class defined within a method
However, I am able to define an anonymous inner class outside a method:
public class Outer {
Foo ex = new Foo {
#Override
public void bar() {
System.out.println("This is my bar implementation");
}
}
}
void TestClass {
public static void main(String[] args) {
Outer outer = new Outer();
outer.ex.bar();
}
}
Is the book wrong in saying that an anonymous inner class is a local inner class as it doesn't have to be local (within a method) or is the example I provided not an anonymous inner class (as it is assigned to a named variable)?
Thanks

ex is not a local class. anything that a local class cannot be anonymous and vice-versa (to the best of my knowledge)
Quoting from Oracle's Java OO tutorial on Anonymous Classes :
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
Couple of lines below ..
While local classes are class declarations, anonymous classes are expressions, which means that you define the class in another expression

Related

Instantiating an inner class within a main method

When we try to instantiate an Inner class (aka: non-static Nested class) in java, say we do that in two cases:
1.in a main method in the same file of the outer Class in which we have two options: (ex:)
public class Test1
{
class InnerClass
{
}
public static void main(String[] args)
{
InnerClass inner = new Test1().new InnerClass();
}
}
or :
public class Test1
{
class InnerClass
{
}
public static void main(String[] args)
{
Test1.InnerClass inner = new Test1().new InnerClass();
}
}
In a another class (say different file), then we have the second option only and using the first option requires us (of course) to import the InnerClass..,
Q: could you please explain why do we have the first option (without any import required) in the first case (the main method in the same file)?
Edit:
I guess the answer to the first question is some how related to the core idea of inner classes. but then +Q:
Q: Isn't an inner class a regular-member of an outer class, so if the inner class is not declared static (static nested class) then I suppose it is a non-static member and consequently its reference type, so why are we able to declare it within a static context (static method) ?
Simply, it is because when you instantiate the inner class from a main method outside the class in which the inner class is present, the Java compiler has no way on knowing inside which class lies that inner class. Hence you have to do
Test1.InnerClass innerClassObject = ...
instead of
InnerClass innerClassObject = ...
An instance of InnerClass can exist only within an instance of
OuterClass and has direct access to the methods and fields of its
enclosing instance.
To instantiate an inner class, you must first instantiate the outer
class. Then, create the inner object within the outer object with this
syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
From Oracle Docs : https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Java nested classes issue

As I have recently started programming, I was a little stuck in this area of coding.
There is a programming lesson named nested classes. But when I want to use it, it actually does not do what the homework wants. Here is an example of what I need to achieve:
public class Zoo {
...
public static class monkey {
...
}
}
and in the main
Zoo zoo1 = new Zoo();
...
zoo1.monkey.setage(int);
...
But there is a problem here that whenever I want to call monkey from zoo1, the debugger says that it's not possible.(Remember that I want to do this without creating an instance of monkey)
Thanks in advance
Update: I am just wondering if it's a kinda language limitation, then how the oracle itself could do that rather easily with system.out.printf?
You can not access the monkey class via an instance of Zoo, it would not actually make any sense to do that. If you want to access static methods of monkey from the main you can just use the example below
public class Zoo {
public static void main(String[] args) {
// Example 1
monkey.setage(3);
// Example 2
Zoo.monkey.setage(3);
}
public static class monkey {
private static int age;
public static void setage(int age) {
monkey.age = age;
}
}
}
But what are you actually trying to accomplish?
monkey looks static to me. They should be public instead of Public, though.
I would say that setage() is not a static method. If that's the case, and if age is a property of a monkey, than it wouldn't make sense to call it statically -- whose age would you be setting?
The problem though is that you can't seem to be able to access the static inner class through a variable of the outer class type.
So it should be Zoo.monkey instead of zoo1.monkey.
If you just want to control scoping or naming, you can use packages.
For example, you could have the following:
package com.example.application.feature;
public class MyClass {
public void f() {
System.out.println("Hello");
}
}
in a source file called com/example/application/feature/MyClass.java.
Edit: I didn't see you note "(Remember that I want to do this without creating an instance of monkey)"
sometimes before asking, searching might help you to save some time.Direct Quotion from this address: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Inner Classes
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.
Objects that are instances of an inner class exist within an instance
of the outer class. Consider the following classes:
class OuterClass {
...
class InnerClass {
...
} }
An instance of InnerClass can exist only within an instance of
OuterClass and has direct access to the methods and fields of its
enclosing instance. The next figure illustrates this idea.
An Instance of InnerClass Exists Within an Instance of OuterClass
To instantiate an inner class, you must first instantiate the outer
class. Then, create the inner object within the outer object with this
syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Additionally, there are two special kinds of inner classes: local
classes and anonymous classes (also called anonymous inner classes).
Both of these will be discussed briefly in the next section.

Java anonymous class and reachable private variable

interface Test {
public void test();
}
public class TestMain {
private String h = "AAA";
public static void main(String[] args) {
TestMain t = new TestMain();
}
public TestMain() {
Test t = new Test() {
public void test() {
System.out.println( h );
}
};
t.test();
}
}
The above source works well.
But I think the variable 'h' should be unreachable from the anonymous class.
I need to know why it works well.
Thank you for all of your help in advance!
Each instance of a non-static inner class has an enclosing instance -- an instance of the outer class which it tied to it via a reference variable stored in the inner class object. All the members of the enclosing instance of available to the inner class object via that reference.
The compiler takes care of adding that reference variable, of course, as well as some special accessor functions that the inner class object can use to get to the outer class object's private members. You can see these accessor functions by disassembling the outer class using javap -c.
The basic rule for determining accessibility to private members is, according to section 6.6.1 of the Java Language Specification:
[I]f the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class that encloses the declaration of the member or constructor.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

use of "this" and "class" as members

I have seen Java code that says something like:
SomeClass.this.someMethod(someArg);
Blah(AnotherClass.class);
Blah(YAClass.this);
What do "this" and "class" mean here? I am used to them as keywords to refer to the current object and to define a class, but this is different. My Java book and online searches have not yielded any explanation.
SomeClass.this/YAClass.this - the this reference of an inner class' enclosing SomeClass/YAClass class.
class SomeClass {
private InnerClass {
public void foo() {
SomeClass outerThis = SomeClass.this;
[...]
}
}
}
(You need to be very careful which this you get particularly when dealing with operations that could be applied to any Object reference. A common case is syncronising on this in an inner class, when the code should be synchronising on the outer instance (a better approach in this case is to use an explicit lock object).)
AnotherClass.class - the java.lang.Class object for the AnotherClass class. Prior to Java 1.5 this was implemented using Class.forName (initialising the class); from 1.5 the ldc bytecode has been extended for direct support.
Class<AnotherClass> clazz = AnotherClass.class;
Both were introduced in Java 1.1.
A quick example for inner class, to complete the other answers:
class SomeClass {
public void someMethod() {
System.out.println("Hello, I have someMethod");
}
public void otherMethod() {
addListener(new MyListener() {
public void someMethod () {
System.out.println("I too, have someMethod");
}
public void listen() {
// I will call someMethod of SomeClass:
SomeClass.this.someMethod();
}
});
}
}
The .class syntax refers to a particular instance of the Class class.
The .this syntax is usually used from within inner classes to refer to the enclosing instance of the top-level class. If you used just this from within an inner class it would refer to the instance of the inner class and not the enclosing class.
.class refers to the Class object corresponding to your instance's class. Java keeps one Class around in memory per referenced type.
Here is the Javadoc for Class: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html
The only time I have seen SomeClass.this used is when you are dealing with nested classes, and need to refer to the instance of the outer class from the inner class. See here for an example: http://juixe.com/techknow/index.php/2009/04/07/java-nested-inner-class-this/

Static nested class in Java, why?

I was looking at the Java code for LinkedList and noticed that it made use of a static nested class, Entry.
public class LinkedList<E> ... {
...
private static class Entry<E> { ... }
}
What is the reason for using a static nested class, rather than an normal inner class?
The only reason I could think of, was that Entry doesn't have access to instance variables, so from an OOP point of view it has better encapsulation.
But I thought there might be other reasons, maybe performance. What might it be?
Note. I hope I have got my terms correct, I would have called it a static inner class, but I think this is wrong: http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
The Sun page you link to has some key differences between the two:
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
...
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
There is no need for LinkedList.Entry to be top-level class as it is only used by LinkedList (there are some other interfaces that also have static nested classes named Entry, such as Map.Entry - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.
As Jon Skeet points out, I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.
To my mind, the question ought to be the other way round whenever you see an inner class - does it really need to be an inner class, with the extra complexity and the implicit (rather than explicit and clearer, IMO) reference to an instance of the containing class?
Mind you, I'm biased as a C# fan - C# doesn't have the equivalent of inner classes, although it does have nested types. I can't say I've missed inner classes yet :)
There are non-obvious memory retention issues to take into account here. Since a non-static inner class maintains an implicit reference to it's 'outer' class, if an instance of the inner class is strongly referenced, then the outer instance is strongly referenced too. This can lead to some head-scratching when the outer class is not garbage collected, even though it appears that nothing references it.
Static inner class is used in the builder pattern. Static inner class can instantiate it's outer class which has only private constructor. You can not do the same with the inner class as you need to have object of the outer class created prior to accessing the inner class.
class OuterClass {
private OuterClass(int x) {
System.out.println("x: " + x);
}
static class InnerClass {
public static void test() {
OuterClass outer = new OuterClass(1);
}
}
}
public class Test {
public static void main(String[] args) {
OuterClass.InnerClass.test();
// OuterClass outer = new OuterClass(1); // It is not possible to create outer instance from outside.
}
}
This will output x: 1
static nested class is just like any other outer class, as it doesn't have access to outer class members.
Just for packaging convenience we can club static nested classes into one outer class for readability purpose. Other than this there is no other use case of static nested class.
Example for such kind of usage, you can find in Android R.java (resources) file.
Res folder of android contains layouts (containing screen designs), drawable folder (containing images used for project), values folder (which contains string constants), etc..
Sine all the folders are part of Res folder, android tool generates a R.java (resources) file which internally contains lot of static nested classes for each of their inner folders.
Here is the look and feel of R.java file generated in android:
Here they are using only for packaging convenience.
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.techpalle.b17_testthird;
public final class R {
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int main=0x7f070000;
}
public static final class string {
public static final int action_settings=0x7f050001;
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050002;
}
}
Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class. So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.
As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a "struct" in C, consider making it static.
From http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html:
Use a non-static nested class (or inner class) if you require access
to an enclosing instance's non-public fields and methods. Use a static
nested class if you don't require this access.
Simple example :
package test;
public class UpperClass {
public static class StaticInnerClass {}
public class InnerClass {}
public static void main(String[] args) {
// works
StaticInnerClass stat = new StaticInnerClass();
// doesn't compile
InnerClass inner = new InnerClass();
}
}
If non-static the class cannot be instantiated exept in an instance of the upper class (so not in the example where main is a static function)
One of the reasons for static vs. normal have to do with classloading. You cannot instantiate an inner class in the constructor of it's parent.
PS: I've always understood 'nested' and 'inner' to be interchangeable. There may be subtle nuances in the terms but most Java developers would understand either.
Non static inner classes can result in memory leaks while static inner class will protect against them. If the outer class holds considerable data, it can lower the performance of the application.
JVM knows no nested classes. Nesting is just syntactic sugar.
Below images shows Java file:
Below images show class files representation of the java file :
Notice that 2 class files are generated, one for parent and another for nested class.
Non-static nested class' objects have access to the enclosing scope. That access to the enclosing scope is maintained by holding an implicit reference of the enclosing scope object in the nested object
Nested class is a way to represent the intent that the nested class type represents a component of the parent class.
public class Message {
private MessageType messageType; // component of parent class
public enum MessageType {
SENT, RECEIVE;
}
}
class Otherclass {
public boolean isSent(Message message) {
if (message.getMessageType() == MessageType.SENT) { // accessible at other places as well
return true;
}
return false;
}
}
private static nested class represents Point#3 & the fact the nested type can only be the subcomponent to the parent class. It can't be used separately.
public class Message {
private Content content; // Component of message class
private static class Content { // can only be a component of message class
private String body;
private int sentBy;
public String getBody() {
return body;
}
public int getSentBy() {
return sentBy;
}
}
}
class Message2 {
private Message.Content content; // Not possible
}
More details here.
I don't know about performance difference, but as you say, static nested class is not a part of an instance of the enclosing class. Seems just simpler to create a static nested class unless you really need it to be an inner class.
It's a bit like why I always make my variables final in Java - if they're not final, I know there's something funny going on with them. If you use an inner class instead of a static nested class, there should be a good reason.
Using a static nested class rather than non-static one may save spaces in some cases. For example: implementing a Comparator inside a class, say Student.
public class Student {
public static final Comparator<Student> BY_NAME = new ByName();
private final String name;
...
private static class ByName implements Comparator<Student> {
public int compare() {...}
}
}
Then the static ensures that the Student class has only one Comparator, rather than instantiate a new one every time a new student instance is created.
Adavantage of inner class--
one time use
supports and improves encapsulation
readibility
private field access
Without existing of outer class inner class will not exist.
class car{
class wheel{
}
}
There are four types of inner class.
normal inner class
Method Local Inner class
Anonymous inner class
static inner class
point ---
from static inner class ,we can only access static member of outer class.
Inside inner class we cananot declare static member .
inorder to invoke normal inner class in static area of outer class.
Outer 0=new Outer();
Outer.Inner i= O.new Inner();
inorder to invoke normal inner class in instance area of outer class.
Inner i=new Inner();
inorder to invoke normal inner class in outside of outer class.
Outer 0=new Outer();
Outer.Inner i= O.new Inner();
inside Inner class This pointer to inner class.
this.member-current inner class
outerclassname.this--outer class
for inner class applicable modifier is -- public,default,
final,abstract,strictfp,+private,protected,static
outer$inner is the name of inner class name.
inner class inside instance method then we can acess static and instance field of outer class.
10.inner class inside static method then we can access only static field of
outer class.
class outer{
int x=10;
static int y-20;
public void m1() {
int i=30;
final j=40;
class inner{
public void m2() {
// have accees x,y and j
}
}
}
}

Categories