473,320 Members | 2,006 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Local Class Question

I'm just getting up to speed on Java, and have a question about local class
behavior. Here's a mini-app to illustrate:

interface Foo { void print(); }

class LocalClassTest
{
public static void main(String[] args) {
Foo foo = getFooImpl(100);
foo.print();
}

public static Foo getFooImpl(final int i) {
class FooImpl implements Foo {
public void print() {
System.out.println("i = " + i);
}
}
return new FooImpl();
}
}

As expected (at least, as I expect) this code prints "i = 100". But what
bugs me is where does this come from? By the time I call "foo.print" the
method "getFooImpl" has returned, and its local variables/parameters should
have been flushed off the stack, along with the value "100" that eventually
gets printed. The only way I can see this as working is that the compiler
has somehow promoted the parameter "i" in "getFooImpl" into a hidden field
within class FooImpl, but I cannot find any docs about this anywhere. Or is
"i" really a reference and has FooImpl grabbed a shadow(y) ref to it?

Any of you experts care to shed some light on this?

Thanks,
Tim

Jul 17 '05 #1
3 2860
Tim Hill wrote:
I'm just getting up to speed on Java, and have a question about local class
behavior. Here's a mini-app to illustrate:

interface Foo { void print(); }

class LocalClassTest
{
public static void main(String[] args) {
Foo foo = getFooImpl(100);
foo.print();
}

public static Foo getFooImpl(final int i) {
class FooImpl implements Foo {
public void print() {
System.out.println("i = " + i);
}
}
return new FooImpl();
}
}

As expected (at least, as I expect) this code prints "i = 100". But what
bugs me is where does this come from? By the time I call "foo.print" the
method "getFooImpl" has returned, and its local variables/parameters should
have been flushed off the stack, along with the value "100" that eventually
gets printed. The only way I can see this as working is that the compiler
has somehow promoted the parameter "i" in "getFooImpl" into a hidden field
within class FooImpl, but I cannot find any docs about this anywhere. Or is
"i" really a reference and has FooImpl grabbed a shadow(y) ref to it?


Tim,

You've hit the nail on the head with your first explanation. The
compiler does indeed turn the local variable i into a instance variable
on the FooImpl class.

Something to keep in mind is that all of this local and inner class
stuff is done 100% by the compiler. The JVM does not know anything
about it. So when an inner class does something that an ordinary class
would not be able to do (like access private data of the outer class)
the compiler adds methods and instance variables as it sees fit to make
this work.

Also, local classes aren't really commonly used. More common is the
anonymous class. Here's you example re-written as an anonymous class:

interface Foo { void print(); }

class LocalClassTest
{
public static void main(String[] args) {
Foo foo = getFooImpl(100);
foo.print();
}

public static Foo getFooImpl(final int i) {
return new Foo() {
public void print() {
System.out.println("i = " + i);
}
};
}
}

If you are just beginning with Java, I wouldn't recommend focusing on
inner and local classes at first. They have quite a few nuances.

HTH,
Ray

Jul 17 '05 #2
Thanks Ray, good to know I'm not going mad. I'd also investigated the anon
class for this behavior using exactly the example you showed!

Also, I agree with the general advice about not getting into these fiddly
fringe things -- just filling in my knowledge of Java (I'm a C++ veteran, so
not too scared of the wrinkles, which compared to C++ are thankfully few and
far between in Java :)

-Tim

"Raymond DeCampo" <rd******@hold-the-spam.twcny.rr.com> wrote in message
news:BT******************@twister.nyroc.rr.com...
Tim Hill wrote:
I'm just getting up to speed on Java, and have a question about local class behavior. Here's a mini-app to illustrate:

interface Foo { void print(); }

class LocalClassTest
{
public static void main(String[] args) {
Foo foo = getFooImpl(100);
foo.print();
}

public static Foo getFooImpl(final int i) {
class FooImpl implements Foo {
public void print() {
System.out.println("i = " + i);
}
}
return new FooImpl();
}
}

As expected (at least, as I expect) this code prints "i = 100". But what
bugs me is where does this come from? By the time I call "foo.print" the
method "getFooImpl" has returned, and its local variables/parameters should have been flushed off the stack, along with the value "100" that eventually gets printed. The only way I can see this as working is that the compiler has somehow promoted the parameter "i" in "getFooImpl" into a hidden field within class FooImpl, but I cannot find any docs about this anywhere. Or is "i" really a reference and has FooImpl grabbed a shadow(y) ref to it?


Tim,

You've hit the nail on the head with your first explanation. The
compiler does indeed turn the local variable i into a instance variable
on the FooImpl class.

Something to keep in mind is that all of this local and inner class
stuff is done 100% by the compiler. The JVM does not know anything
about it. So when an inner class does something that an ordinary class
would not be able to do (like access private data of the outer class)
the compiler adds methods and instance variables as it sees fit to make
this work.

Also, local classes aren't really commonly used. More common is the
anonymous class. Here's you example re-written as an anonymous class:

interface Foo { void print(); }

class LocalClassTest
{
public static void main(String[] args) {
Foo foo = getFooImpl(100);
foo.print();
}

public static Foo getFooImpl(final int i) {
return new Foo() {
public void print() {
System.out.println("i = " + i);
}
};
}
}

If you are just beginning with Java, I wouldn't recommend focusing on
inner and local classes at first. They have quite a few nuances.

HTH,
Ray

Jul 17 '05 #3
Just to add a bit more, an method inner class as you have below can only
access method variables that are declared final. By declaring them final
they are not existing on the stack in this case.
"Tim Hill" <no****@span.com> wrote in message
news:xMfrb.108286$9E1.537659@attbi_s52...
I'm just getting up to speed on Java, and have a question about local class behavior. Here's a mini-app to illustrate:

interface Foo { void print(); }

class LocalClassTest
{
public static void main(String[] args) {
Foo foo = getFooImpl(100);
foo.print();
}

public static Foo getFooImpl(final int i) {
class FooImpl implements Foo {
public void print() {
System.out.println("i = " + i);
}
}
return new FooImpl();
}
}

As expected (at least, as I expect) this code prints "i = 100". But what
bugs me is where does this come from? By the time I call "foo.print" the
method "getFooImpl" has returned, and its local variables/parameters should have been flushed off the stack, along with the value "100" that eventually gets printed. The only way I can see this as working is that the compiler
has somehow promoted the parameter "i" in "getFooImpl" into a hidden field
within class FooImpl, but I cannot find any docs about this anywhere. Or is "i" really a reference and has FooImpl grabbed a shadow(y) ref to it?

Any of you experts care to shed some light on this?

Thanks,
Tim

Jul 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Nan Li | last post by:
I just discovered you can have a local class defined inside a function like this: #include <iostream> using namespace std; int main(int argc, char* argv) {
0
by: Manfred Braun | last post by:
Hi All, I've already asked another question , but this is finally the same issue. I cannot execute two asynchron WMI queries on the local machine, one after the other. The original question is...
9
by: Stefan Turalski \(stic\) | last post by:
Hi, I done sth like this: for(int i=0; i<10; i++) {...} and after this local declaration of i variable I try to inicialize int i=0;
23
by: Timothy Madden | last post by:
Hello all. I program C++ since a lot of time now and I still don't know this simple thing: what's the problem with local functions so they are not part of C++ ? There surely are many people...
55
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in...
1
by: jcprince | last post by:
Hi Not sure I can do what I'm trying to do without using a 3rd party component like Dart. I need to build a windows service to create a socket connection on an IBM mainframe using an IP and port...
2
by: A.J. Bonnema | last post by:
Hi all, I just started using Python. I used to do some Java programming, so I am not completely blank. I have a small question about how classes get instantiated within other classes. I have...
7
by: pauldepstein | last post by:
#include <iostream> using namespace std; double & GetWeeklyHours() { double h = 46.50; double &hours = h; return hours; }...
11
by: cj | last post by:
Perhaps someone knows how to do this. When I open a new ASP.NET web service application in VS 2008, it opens with a simple Hello World web service already written. I want to see this work. ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.