473,666 Members | 2,087 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(fina l int i) {
class FooImpl implements Foo {
public void print() {
System.out.prin tln("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 2881
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(fina l int i) {
class FooImpl implements Foo {
public void print() {
System.out.prin tln("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(fina l int i) {
return new Foo() {
public void print() {
System.out.prin tln("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******@hol d-the-spam.twcny.rr.c om> wrote in message
news:BT******** **********@twis ter.nyroc.rr.co m...
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(fina l int i) {
class FooImpl implements Foo {
public void print() {
System.out.prin tln("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(fina l int i) {
return new Foo() {
public void print() {
System.out.prin tln("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.co m> wrote in message
news:xMfrb.1082 86$9E1.537659@a ttbi_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(fina l int i) {
class FooImpl implements Foo {
public void print() {
System.out.prin tln("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
3326
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
2491
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 based on complicated code. So I reduced the "kernel" to a small C# sample , which shows the problem. The question is: - Is this a problem with my code, as not freeing resources etc? - Is this possibly a WMI issue?
9
2201
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
3993
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 who will find them very helpfull. gcc has them as a non-standard option, but only when compiling C language code, so I'm afraid there might be some obscure reason why local functions are not so easy to be dealt with in C++, which I do not yet know.
55
6202
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 C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
1
3629
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 combination. No problem there. However, due to the expected volume (at least 20x10K streams per second in each direction), the mainframe sysadmin has requested the service use multiple 'conversations' within the single IP connection. The...
2
1986
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 added the source of a test program to the bottom of this mail, that contains 3 methods within a testclass that each instantiate the same class and bind it to a local variable. My understanding was, that the local variable gets garbage collected as...
7
6669
by: pauldepstein | last post by:
#include <iostream> using namespace std; double & GetWeeklyHours() { double h = 46.50; double &hours = h; return hours; } //---------------------------------------------------------------------------
11
2997
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. Without changing a thing I built the solution and published it to localhost default web site. How can I test it?????
0
8449
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8360
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8876
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8784
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8556
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7387
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4371
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.