• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Access control of Anonnymous inner class

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Q.(1) Can a anonymous class be static? if yes then , what types
of methods and variables of outer class an anonymous class can
access ?
Q.(2) This is from some notes.
String s = "message";
Frame f = new Frame();
f.add(btn);
btn.addActionListener(
new ActionListener() {
void ActionPerformed() {System.out.println(s);}
}
);
f.pack();
f.setVisible();
What will you see on screen?
A. Output "message"
B. compile OK, but nothing is shown because the button is not properly added
C. compiler error because s can not be used there
D. compiler error because the listener is not constructed correctly
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Pinky
the second question u have written out is wrong
u have not constructed the button properly
u r adding the button before declaring it
 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is answer to your first question.
Yes. Anonymous classes can be static provided they are defined as an expression in the static context.
eg :
public class A
{
static int count;

A(){
count++;
}
static Integer howManyObjects()
{
return (new Integer(count));
}
}
It can access all static members of enclosing context and local final variables.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Pinky;
Q.(1) - No, an anonymous class can never be static. See JLS 2e 15.9.5. If if could be static, then it could only access static methods and variables of the outer class, but it can't so that's just theorizing.
Note that the example provided by Ramesh does not define any inner classes - static, anonymous, or otherwise. The <code>return</code> statement creates a new instance of an existing class (<code>Integer</code>) but does not derive a new subclass, which is required to declare an anonymous class. You couldn't use <code>Integer</code> as the superclass of an anonymous class anyway, because <code>Integer</code> is <code>final</code>.
Q.(2) The correct answer is D. The <code>ActionListener</code> is not implemented properly; the <code>ActionPerformed</code> method takes an <code>ActionEvent</code> argument. The use of the word "constructed" in the question is a bit misleading; it seems to imply that the constructor of the anonymous class implementing <code>ActionListener</code> is faulty. Anonymous classes cannot have constructors because the name of a constructor is the same as the name of its class and anonymous classes have no name - they're anonymous. Lots of authors make grammatical and semantic mistakes in their use of human language; they seem to think if they get the computer language part right then that's all that matters.
About the other choices - A is wrong because the code won't compile; B is wrong because the button is properly added, and C is wrong because <code>s</code> is perfectly accessible to code inside anonymous classes.
 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One more reason why the Listener implementation is incorrect is that the actionPerformed method is declared with package level access in this code. The compiler will object to this since the actionPerformed method is declared as a public method in the ActionListener interface and you cannot override it to be more private.
 
Ramesh Donnipadu
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jply,
I do believe anonymous classes declared in static context are static anonymos classes.
Usually anonymous classes are defined and instantiated in contexts where a reference can be used. For example, return value of a method, or as an argument in a method call or in initialization of variables. If the context in which an anonymous class is being defined happens to be static, then don't we call such a class 'anonymous static class'?
Sorry. the example I gave in the previous posting was not right.
Consider this.
interface Iface {
void inWords();
}
class A
{
static int count;

A(){
count++;
}
public static Iface howManyObjects() {
return new Iface(){
public void inWords()
{
String number = "";
switch(count) {
case 1 : number = "One";
break;
case 2 : number = "Two";
break;
case 3 : number = "Three";
break;
case 4 : number = "Four";
break;
case 5 : number = "Five";
break;
default: number = "Big number";
}
System.out.println("# of objects created is : "+number);
return;
}
};
}
}
public class tester
{
public static void main(String args[])
{
int index = (args.length < 1)?5:args.length;

for (int i=0; i<index; i++) {>
A aObj = new A();
}
Iface i1 = A.howManyObjects();
i1.inWords();
return;
}
}
Isn't the class defined - as a return type in howManyObjects() method - an anonymous class? Since the enclosing context is static, can't we call it an anonymous static class?
(Incidentally, this class has access to static variable of the class A )
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You've put together a good one here, and I see your point. I modified your code to give a tougher test:
<pre><code>
interface Iface {
void inWords();
}
class A {
static int count;
A() {
count++;
}
public static Iface howManyObjects() {
return new Iface() {
public void inWords() {
System.out.println("# of objects created is : " + count);
return;
}
};
}
public Iface howManyObjects2() {
return new Iface() {
public void inWords() {
System.out.println( "count = " + count );
}
};
}
}
public class tester {
public static void main(String args[]) {
Iface i1 = A.howManyObjects();
i1.inWords();
try {
Object obj = Class.forName( "A$1" ).newInstance();
((Iface)obj).inWords();
Object obj2 = Class.forName( "A$2" ).newInstance();
((Iface)obj2).inWords();
} catch (Exception e) {
System.out.println( e );
}
return;
}
}
</code></pre>
In <code>main</code>, we're now actually attempting to create instances of anonymous classes directly. Since they don't have names we have to use the names of the class files to slip through the back door. (I also shortened your example a bit, hope you don't mind.) When we run this, we get: first your original output, next the output from the anonymous class declared in the static context (A$1), and finally an <code>InstantiationException</code> when we try to create an instance of the anonymous class declared in the non-static context. Since you can create an instance of a nested class without an enclosing instance only if the nested class is static, the implication is that <code>A$1.class</code> is indeed the class file of a static class, at least for all practical purposes.
Yes, the class is declared in a static context, and as such cannot access non-static variables of its enclosing class (I checked that behavior too, but I left it out of this example), and it can be created without an instance of its enclosing class. That sounds like <code>static</code> to me. If you're preparing for SCJP, however, I'd go with the spec - that's what's being tested.
Good stuff.
jply
 
We've gotta get close enough to that helmet to pull the choke on it's engine and flood his mind! Or, we could just read this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic