Inner Class Question
My question pertains to the code at the bottom of this post.
I don't understand why the compiler doesn't give an error for the line below. Why would it let you refer to something inside the class (in this case I'm referring to ClassWithInnerClass.MyInnerClass) unless it were static?
ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();To illustrate why I'm asking, I created 2 ints ("regularInt" and "staticInt") inside class "ClassWithInnerClass". The compiler let me set the value of "staticInt" from within main whereas it wouldn't let me do so w/ "regularInt" (which is why I commented that line out). Don't get me wrong though - I understand the reasons why the compiler behaves as it does for "regularInt" and "staticInt". I understand that a static variable can be accessed without instantiating a class (and that there's only 1 created no matter how many classes are instantiated). I also understand that, to access a non-static variable, you need to instantiate a class. My question arises only because of trying to extend that logic to MyInnerClass.
I can already take a guess that the answer is going to be something like, "the reason it works this way is because class 'MyInnerClass' is just a declaration NOT a definiton". I guess I just want confirmation of this and, if possible, some reasoning behind this logic.
HERE'S THE CODE...
class CreateInnerClasses {
public static void main (String args[]) {
ClassWithInnerClass cwic = new ClassWithInnerClass();
ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();
//ClassWithInnerClass.regularInt = 5;
ClassWithInnerClass.staticInt = 10;
mic.printIt();
class ClassWithInnerClass {
public int regularInt ;
static public int staticInt;
class MyInnerClass {
void printIt() {
System.out.println("Inside ClassWithInnerClass.myInnerClass");
MyInnerClass retMyInnerClass () {
return new MyInnerClass();
The line ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();is accepted because the name of the inner class is ClassWithInnerClass.MyInnerClass. This has nothing to do with accessing fields even though the syntax is similar.
On the other hand, the line SomeClassWithAnInnerClass.InnerClass ic = new SomeClassWithAnInnerClass.InnerClass();is not accepted because the nested class SomeClassWithAnInnerClass.InnerClass is not static: you must have an instance of the outer class available. The correct syntax for calling the constructor of the inner class would be Outer.Inner instance = outerInstance.new Inner();In this case you could write: ClassWithInnerClass.MyInnerClass mic = new SomeClassWithAnInnerClass() . new InnerClass();
// OR:
ClassWithInnerClass.MyInnerClass mic = cwic . new InnerClass();The Java tutorial has a pretty good explanation on nested classes:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html
Similar Messages
-
Hi guys,
I have a question to ask - when i'm writing an inner class and i want to create a new instance from it, the Eclipse forces me to use an instance of the containing class to call new.
Is it how it's done or am i doing something wrong?
public class A
// Some code here
public class B
//Some code here
}Trying to create an instance:
A a = new A();
A.B b = a.new B();What you have defined is "non-static" inner class.A "non-static" can only be instantiated only if we create an object of outer class.True.
>
There are two ways to create "inner" class object,
1)The way you have written the codeTrue.
2)
public class A
{ // Some code here
public void createInner()
classB b=new ClassB();
public classB
//Some code here
That code won't compile. Even if you corrected it so that it did compile, it doesn't really help in the OP's situation. Did you read the advice of Saish and Jos about why class 'B' probably shouldn't be public, anyway? -
Anonymous Inner Class question
How can I get "foof" to be echoed to the screen?
class MyClass {
void go() {
Bar b = new Bar();
b.doStuff(new Foo() {
public void foof() {
System.out.println("foof");
interface Foo {
void foof();
class Bar {
void doStuff(Foo f) {}
public class TestWonder {
public static void main (String... args) {
new MyClass().go();
//Why doesn't this print out "foof" to the screen? Nothing is echoed to the screen.
}Sorry to be so thick, but I thought that the code did that already. Apparently it doesn't. In other words, how would the code invoke the override foof()? I should be clearer:
I know if I change Bar's doStuff() to
void doStuff(Foo f) {
System.out.println("bar's dostuff");
}then when go() is executed bar's dostuff will print out. But, what about the override in the anonymous inner class?
Edited by: RonNYC2 on Feb 5, 2010 1:03 PM
Edited by: RonNYC2 on Feb 5, 2010 1:05 PM -
Write a java file and compile it. The compiled class size is X. Add an inner class and the size increases as well as adding another class file.
Decompile both.
You will see that the entire inner class is defined in the outer class as well as being in it's own class. Why is this necessary? Since you reference an inner class by using the outer class name, why do you need to have a separate inner class.class file generated?
Thanks
STYou will see that the entire inner class is defined in
the outer class as well as being in it's own class.No, that is not true. The inner class is defined only in a separate class file.
Why is this necessary? Since you reference an inner
class by using the outer class name, why do you need
to have a separate inner class.class file generated?Because inner classes was an addition to the Java language that the JVM does not know about. Therefore inner classes are translated into ordinary classes by the compiler. -
Annoyomous Inner class question
Is the test instance simply an instance of an annoyomous class which extends the MyClass class and provides a different implementation of it's printStuff() method?
I want to make sure I understand why annoyomous class can be useful.
Thanks ...
class Tester {
MyClass test = new MyClass(){
protected void printStuff(){
System.out.println("Annoyomous class");
class MyClass {
protected void printStuff(){
System.out.println("Original class");
}I've read 2 chapters from different books on Anonymous Inner classes but I need to be sure I've grasped the concepts in my own head.
I have replaced
class Tester {
MyClass test = new MyClass(){
protected void printStuff(){
System.out.println("Annoyomous class");
}With
class Tester {
MyClass test = new MyNewClass();
class MyNewClass extends MyClass {
protected void printStuff(){
System.out.println("Annoyomous class");
}This works the same way so
Is the latter a more compact way to do one off extension and instaniation of a class.
Would the latter be a better solution if you need to create more than one instance of the same anonymous class? -
Exception handling for eventlistener inner classes in swing application
Hi,
This is probably sooo easy I will kick myself when I find out, but anyway here goes...
I have an inner class thus...
cmbOffence.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
cmbOffence_focusGained(e);
public void focusLost(FocusEvent e) {
try {
cmbOffence_focusLost(e);
} catch (XMLConfigurationException xce) {
});where cmbOffence.focusLost(e) is looking up to a class that throws an exception which should be fatal i.e. the swing app should close. I want to handle this exception gracefully so therefore want to throw the XMLConfiguratinException to the main application class. How do I do this?? I guess this is more of an inner classes question than a swing one per se, but any help would be appreciated.
Thanks
ConradI think you're maybe confusing classes and threads. In the typical Swing application the "main" thread finishes after openning the initial window and there really is no main thread to report back to. In fact the dispatcher thread is about as "main" as they come.
To exit such a program gracefully is usually a matter of cleaning up resources and calling dispose on the main window, which you can perfectly well do from the dispatcher thread.
I usually wind up with some centralised method to deal with unexpected exceptions, for example as part of my desk top window in an MDI, but it's called from the dispatcher thread as often as from anywhere. -
Design question on inner class
I have an app, with a JPanel. The way I have it setup right now is the JPanel is an inner class with an overloaded constructor. I call the inner class depending on the arguements. this is done repeatedly in my program.
My question is: Should I be doing it this way or maybe as a method that returns the updated JPanel? Can this cause serious memory problems?
example
private void CreateTextfields(int q, int c){
// c = number of choices selected from other JComboBox
// q = question selected from combo box
// questions is the arrylist containing all questions
AnswerPanel answerPanel;
answerPanel = null;
textFieldPanel.removeAll();
if( questions.isEmpty() && c > 0 ){
answerPanel = new AnswerPanel(c);
else if( !questions.isEmpty() && c == 0 ){
answerPanel = new AnswerPanel(q, listOfAnswers);
else if( !questions.isEmpty() && c > 0 ){
clearLogic();
answerPanel = new AnswerPanel(q, listOfAnswers, c);
textFieldPanel.add( answerPanel, BorderLayout.CENTER ); Thanks
Jim<<serious memory problems>>
Probably not. But it seems wasteful to keep creating a new object just to set some properties. Why not make a single AnswerPanel, with overloaded setContents() functions?
Not that I'm a Swing expert or anything....
HTH,
Ken -
I have a class that has 3 inner classes, on class read the colors and font settings, how can I pass this class to the 2 other inner classes
Here is a watered down version of code:
class MainClass{
public MainClass(){
// do some stuff
innerClass3 ic = new innerClass3();// I need to pass this to the other inner classes
layeredPane.add( new innerClass1( some Variable), 1);
layeredPane.add( new innerClass2( anotherVariable), 2 );
class innerClass1 extends JTextPane{
public innerClass1( String s ){
// instead of doing this
innerClass3 ic = new innerClass3();
setBackground(ic.getBackground() );
class innerClass2 extends JPanel{
public innerClass2( String[] z){
// and this again
innerClass3 ic = new innerClass3();
setForeground(ic.getFontClor());
class innerClass3{
Color background;
Color foreground;
public innerClass(){
setColors();
public void setColors(){
background = Color.blue;
foreground = Color.red;
public Color getBackground(){
return background;
public Color getFontColor(){
return foreground;
Thanks for the reply
Works well for first screen, but I recall the innerClasses(1 and 2) from an actionPerformed in innerClass2 and I keep getting nullPointerError when referring to innerClass3. Each screen will have different fonts and colors, so I need it to update after each button click.
// this is inside innerClass2( it's panel with buttons )
// the next screens graphics will depend on which button is selected
public void mouseReleased(final java.awt.event.MouseEvent e) {
layeredPane.removeAll();
currentQuestionNumber++;
question = questionText[currentQuestionNumber] ;
// adds a JTextPane with question
layeredPane.add(new innerClass1(question, ic), 1 );
// adds a JPanel with buttons
layeredPane.add(new innerClass2( currentQuestionNumber, ic ), 3 );Will be tearing hair out soon
Jim -
A question about non-static inner class...
hello everybody. i have a question about the non-static inner class. following is a block of codes:
i can declare and have a handle of a non-static inner class, like this : Inner0.HaveValue hv = inn.getHandle( 100 );
but why cannot i create an object of that non-static inner class by calling its constructor? like this : Inner0.HaveValue hv = Inner0.HaveValue( 100 );
is it true that "you can never CREATE an object of a non-static inner class( an object of Inner0.HaveValue ) without an object of the outer class( an object of Inner0 )"??
does the object "hv" in this program belong to the object of its outer class( that is : "inn" )? if "inn" is destroyed by the gc, can "hv" continue to exist?
thanks a lot. I am a foreigner and my english is not very pure. I hope that i have expressed my idea clearly.
// -------------- the codes -------------------
import java.util.*;
public class Inner0 {
// definition of an inner class HaveValue...
private class HaveValue {
private int itsVal;
public int getValue() {
return itsVal;
public HaveValue( int i ) {
itsVal = i;
// create an object of the inner class by calling this function ...
public HaveValue getHandle( int i ) {
return new HaveValue( i );
public static void main( String[] args ) {
Inner0 inn = new Inner0();
Inner0.HaveValue hv = inn.getHandle( 100 );
System.out.println( "i can create an inner class object." );
System.out.println( "i can also get its value : " + hv.getValue() );
return;
// -------------- end of the codes --------------when you want to create an object of a non-static inner class, you have to have a reference of the enclosing class.
You can create an instance of the inner class as:
outer.inner oi = new outer().new inner(); -
Design question about when to use inner classes for models
This is a general design question about when to use inner classes or separate classes when dealing with table models and such. Typically I'd want to have everything related to a table within one classes, but looking at some tutorials that teach how to add a button to a table I'm finding that you have to implement quite a sophisticated tablemodel which, if nothing else, is somewhat unweildy to put as an inner class.
The tutorial I'm following in particular is this one:
http://www.devx.com/getHelpOn/10MinuteSolution/20425
I was just wondering if somebody can give me their personal opinion as to when they would place that abstracttablemodel into a separate class and when they would just have it as an inner class. I guess re-usability is one consideration, but just wanted to get some good design suggestions.It's funny that you mention that because I was comparing how the example I linked to above creates a usable button in the table and how you implemented it in another thread where you used a ButtonColumn object. I was trying to compare both implementations, but being a newbie at this, they seemed entirely different from each other. The way I understand it with the example above is that it creates a TableRenderer which should be able to render any component object, then it sets the defaultRenderer to the default and JButton.Class' renderer to that custom renderer. I don't totally understand your design in the thread
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=680674
quite yet, but it's implemented in quite a bit different way. Like I was saying the buttonClass that you created seem to be creating an object of which function I don't quite see. It looks more like a method, but I'm still trying to see how you did it, since it obviously worked.
Man adding a button to a table is much more difficult than I imagined.
Message was edited by:
deadseasquirrels -
Question about inner class - help please
hi all
i have a question about the inner class. i need to create some kind of object inside a process class. the reason for the creation of object is because i need to get some values from database and store them in an array:
name, value, indexNum, flag
i need to create an array of objects to hold those values and do some process in the process class. the object is only for the process class that contains it. i am not really certain how to create this inner class. i tried it with the following:
public class process{
class MyObject{}
List l = new ArrayList();
l.add(new MyObject(....));
or should i create the object as static? what is the benifit of creating this way or static way? thanks for you help.for this case, i do need to create a new instance of
this MyObject each time the process is running with a
new message - xml. but i will be dealing with the case
where i will need a static object to hold some
property values for all the instances. so i suppose i
will be using static inner class for that case.The two situations are not the same. You know the difference between instance variables and static variables, of course (although you make the usual sloppy error and call them static objects). But the meaning of "static" in the definition of an inner class is this: if you don't declare an inner class static, then an instance of that inner class must belong to an instance of its containing class. If you do declare the inner class static, then an instance of the inner class can exist on its own without any corresponding instance of the containing class. Obviously this has nothing to do with the meaning of "static" with respect to variables. -
Inner classes - a general question
i'm having some difficulties understanding when to use a static inner class
and when to use a non static inner class
lets say i'm implementing a LinkedList , and i want my nodes and my iterator
implemented in inner classes .
when and why should i declare them static or non static.
thank you very much in advance.Inner classes are never static. Nested classes can be either static or non-static; a non-static nested class is called an inner class.
Anyway, an inner class implicitly gets a reference to an object of the outer class, while a static nested class doesn't, so the decision should depend on whether or not it needs that.
An iterator would need a reference to its collection so it would be a non-static nested class. A node wouldn't so it would be a static nested class. -
A question about local inner classes
Suppose an inner class created in a method:
public void thisMethod(final int a){
class InnerClass {
//code
}Why, in order to use the parameter a in the inner class, I have to pass it final?Aurelious wrote:
JoachimSauer wrote:
Because you can't refer to the argument of a method once the method call is completed (since the method argument lives on the stack).Why does that matter? If the parameter is of a primitive type, the object will get a copy of it anyway. If the parameter is not primitive, then the value on the stack will be a reference to the argument and not the argument-object itself. In either case, it should then be safe to modify the value after the method returns, as it will either be the primitive copy or a copy of a reference to the object which is itself not on the stack, so the field referenced by the object is still valid either way.
Am I missing something?If your inner class is using a local variable in the calling method, the expectation is that it's the same variable. But it's not. If it were, then when the stack frame was popped, the variable would be out of scope, which is incompatible with the fact that the inner object can live on.
On the other hand, if we copy it without making it final, then that's misleading. It looks like I have the same variable, but if I change it in the method, it doesn't change in the object, and vice versa.
So we have to make a copy to prevent scope/lifetime problems, and we have to make it final so that the copy can be indistinguishable from it being the same variable. -
Question about anonymous inner class??
Is there any error occurs,If a class declear & implement two anonymous inner classes ??
public class TryItAndSee {
void m() {
Runnable x = new Runnable(){
public void run() {
System.out.println("?");
Runnable y = new Runnable(){
public void run() {
System.out.println("!");
} -
Question on Anonymous Inner class !
Can an Anonymous Inner class implement or extend any thing?
I feel no .. if yes can anyone give an example please..An example: the anonymous inner class in u extends Thread.
$ cat u.java
class u {
public static void main(String a[]) {
Thread t = new Thread ( ) {
public void run() {
System.out.println(getClass().getName());
t.start();
$ javac u.java
$ java u
u$1
$
The same idea but with the Runnable interface (and not class)
$ cat u.java
class u {
public static void main(String a[]) {
Thread t = new Thread ( new Runnable ( ) {
public void run() {
System.out.println(getClass().getName());
t.start();
$ java u
u$1
Maybe you are looking for
-
How do you connect macbook air to dell u2410 monitor using thuderbolt to hdmi
Ive just plugged in my thuderbolt cable to HDMI on the Dell Monitor U2410 and my system preferences can see it but the monitor is saying no VGA cable. Can it support thuderbolt to HDMI? Many thanks
-
Created by and creation date default values on form
Hi Friends, I am a form newbie. I am creating a simple form. I have non-display column/fields: a.) CREATED_BY - how do I put the default value of the user login ID upon inserting record? b.) CREATION_DATE - how do I put the SYSDATE upon inserting the
-
How to make all Button component instances trigger rollOver sound?
Hello all-- I am using the Button component (the one shipped with CS3) in many places in my AS3 project. I am coding in .as files, not on the timeline. I have skinned the Button to use the colors I like. Now I wish to "skin" it so that all instances
-
Any possibility of upgrading Satellite M40 to read 2GB xD memory card?
Hi, According to the User's Manual, the M40 can only read xD-cards up to the size of 512MB. Now I have bought an Olympus camera, including a 2GB xD-card. Is there any way of upgrading the notebook to read this card or is it simply not possible? Thank
-
SW6U2 (C++) wrong code with empty base class
Consider this program: #include <assert.h> #include <new> struct Base1 int i; struct Base2 Base2() struct Derived : public Base1, public Base2 int main( int, char** ) int buf[2] = { 0x7F7F7F7F, 0x7F7F7F7F }; assert( sizeof( Derived ) == 4 ); new (buf