HELP: Inner Class vs. Private Member
I use "javadoc -private" to create documents with inner classes. As a result, all private fields and methods, which I don't need, show up in the same document. Is there any way I can have inner classes without private members?
how do you declare your inner class?
Is it (public)
public static class MyInnerClassor (private)
private static class MyInnerClassor (package)
static class MyInnerClassor (protected)
protected static class MyInnerClassTry to change the way you declare the inner class. Use protected or package or public instead.
Similar Messages
-
Help: Factory Class using Inner Class and Private Constructor?
The situation is as follows:
I want a GamesCollection class that instantiates Game objects by looking up the information needed from a database. I would like to use Game outside of GamesCollection, but only have it instantiated by GamesCollection to ensure the game actually exist. Each Game object is linked to a database record. If a Game object exist, it must also exist in the database. Game objects can never be removed from the database.
I thought about making the Game object an inner class of GamesCollection, but this means that Game class constructor is still visible outside. So what if I made Game constructor private? Well, now I can't create Game objects without a static method inside Game class (static Object factory).
Basically what I need is a constructor for the inner Game class accessible to GamesCollection, but not to the rest of the world (including packages). Is there a way to do this?leesiulung wrote:
As a second look, I was initially confused about your first implementation, but it now makes more sense.
Let me make sure I understand this:
- the interface is needed to make the class accessible outside the outer classBetter: it is necessary to have a type that is accessible outside of GameCollection -- what else could be the return type of instance?
- the instance() method is the object factory
- the private modifier for the inner class is to prevent outside classes to instantiate this objectRight.
However, is a private inner class accessible in the outer class? Try it and see.
How does this affect private/public modifiers on inner classes?Take about five minutes and write a few tests. That should answer any questions you may have.
How do instantiate a GameImpl object? This basically goes back to the first question.Filling out the initial solution:
public interface Game {
String method();
public class GameCollection {
private static class GameImpl implements Game {
public String method() {
return "GameImpl";
public Game instance() {
return new GameImpl();
public static void main(String[] args) {
GameCollection app = new GameCollection();
Game game = app.instance();
System.out.println(game.method());
}Even if you were not interested in controlling game creation, defining interfaces for key concepts like Game is always going to be a good idea. Consider how you will write testing code, for example. How will you mock Game? -
Private inner class with private constructor
I read that if constructor is public then you need a static method to create the object of that class.
But in the following scenario why I am able to get the object of PrivateStuff whereas it has private constructor.
I am messing with this concept.
public class Test {
public static void main(String[] args) {
Test t = new Test();
PrivateStuff p = t.new PrivateStuff();
private class PrivateStuff{
private PrivateStuff(){
System.out.println("You stuff is very private");
}A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
* Otherwise, if 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 (§7.6) that encloses the declaration of the member or constructor. [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.1]
Your main method is within the body of the top level class, so the type (the inner class) and method are accessible.
eg:
class ImInTheSameSourceFileAsInnerAccessTest {
public static void main(String[] args) {
InnerAccessTest t = new InnerAccessTest();
InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
public class InnerAccessTest {
public static void main(String[] args) {
InnerAccessTest t = new InnerAccessTest();
PrivateStuff p = t.new PrivateStuff();
private class PrivateStuff{
private PrivateStuff(){
System.out.println("You stuff is very private");
}Result:
$ javac -d bin src/InnerAccessTest.java
src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
^
src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
^
2 errors
Edited by: pm_kirkham on 20-Jan-2009 10:54 added example of 'in the same source file' -
Help , inner class included.
hello all :
I want to check a java file , which include inner class or not , and I want to get the inner class name of it , how can I do it ?
looks like this :
java InnerClassChecker Mother.java
InnerClassA
InnerClassB
InnerClassC
thank u.I would suggest compiling Mother.java and then you can do this with the Class object of the mother class.
Class c = motherObj.getClass();Then you can call c.getClasses(). This will return all public inner Classes of Mother.
If you dont have the mother Object and want to do it with the parameter it would look like this:
java InnerClassChecker Mother.class
Then your InnerClassChecker takes the <param> in its main method and calls
Class.forName(<param>) to load the Mother class object. -
Compiler bug with generics and private inner classes
There appears to be a bug in the sun java compiler. This problem was reported against eclipse and the developers their concluded that it must be a problem with javac.
Idea also seems to compile the example below. I couldn't find a bug report in the sun bug database. Can somebody tell me if this is a bug in javac and if there is a bug report for it.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=185422
public class Foo <T>{
private T myT;
public T getT() {
return myT;
public void setT(T aT) {
myT = aT;
public class Bar extends Foo<Bar.Baz> {
public static void main(String[] args) {
Bar myBar = new Bar();
myBar.setT(new Baz());
System.out.println(myBar.getT().toString());
private static class Baz {
@Override
public String toString() {
return "Baz";
Eclipse compiles and runs the code even though the Baz inner class is private.
javac reports:
Bar.java:1: Bar.Baz has private access in Bar
public class Bar extends Foo<Bar.Baz>
^
1 errorAs I said in my original post its not just eclipse that thinks the code snippet is compilable. IntelliJ Idea also parses it without complaining. I haven't looked at the java language spec but intuitively I see no reason why the code should not compile. I don't think eclipse submitting bug reports to sun has anything to do with courage. I would guess they just couldn't be bothered.
-
How to call inner class method in one java file from another java file?
hello guyz, i m tryin to access an inner class method defined in one class from another class... i m posting the code too wit error. plz help me out.
// test1.java
public class test1
public test1()
test t = new test();
public class test
test()
public int geti()
int i=10;
return i;
// test2.java
class test2
public static void main(String[] args)
test1 t1 = new test1();
System.out.println(t1.t.i);
i m getting error as
test2.java:7: cannot resolve symbol
symbol : variable t
location: class test1
System.out.println(t1.t.geti());
^There are various ways to define and use nested classes. Here is a common pattern. The inner class is private but implements an interface visible to the client. The enclosing class provides a factory method to create instances of the inner class.
interface I {
void method();
class Outer {
private String name;
public Outer(String name) {
this.name = name;
public I createInner() {
return new Inner();
private class Inner implements I {
public void method() {
System.out.format("Enclosing object's name is %s%n", name);
public class Demo {
public static void main(String[] args) {
Outer outer = new Outer("Otto");
I junior = outer.createInner();
junior.method();
} -
Instantiation an inner class using reflection
I want to instantiate an inner class using the Class.newInstance() method called within the Outer class constructor:
public Outer
public Outer()
Inner.class.newInstance();
private Class Inner { }
When I try it, however, I get an InstantiationException.
Is there some way to do this?
Thanks for the help.
ScottHere is a consolidation of what everyone posted and it does appear to work. In one of your post you used the getDeclaredConstructors() method and said it was less than ideal; I am not sure what you meant but I suspect it was the hard coded array reference. Anyhow I used the getDeclaredConstructor() method which appears to get non-public constructors also and is basically the same as using the getConstructor() method.
import java.lang.reflect.*;
public class Test35 {
static public void main(String[] args) {
Test35 t35 = new Test35();
t35.testIt();
private class Inner {
public String toString() {
return "Hear I am";
public void testIt() {
try {
Constructor con = Inner.class.getDeclaredConstructor(new Class[] {Test35.class});
Inner in = (Inner)con.newInstance(new Object[] {this});
System.out.println(in);
} catch (Exception e) {
e.printStackTrace(); -
Inner Classes Changing Access Rights Of Parent Members
I read that if you access a parent class's private memebers or methods from within an inner class, those members of methods will automatically and silently be converted to having package access. This seems dangerous and I'd like to know how I could design around it.
Here is my current dilemma. I have an EventHandler class whose handleEvent() method changes with the object's state. I've implemented this using the Strategy Pattern, where the Strategy objects are inner classes of EventHandler. The problem is that these Strategy objects need access to certain private members and methods of their parent. There is no reason, however, to give package access to these members and methods. What can I do? Or does this suggest that I need a design change? Other than this issue, though, I'm quite happy with the design.
Thanks for any thoughts,
JohnWhen inner classes access private fields or methods, the compiler generates new package-private methods
with names like "access$000":
import java.lang.reflect.*;
public class X {
private void x() {}
class Y {
public void y() {
x();
public static void main(String[] args) {
Method[] methods = X.class.getDeclaredMethods();
for(int i=0; i<methods.length; ++i)
System.out.println(methods.getName());
So it's not correct that the access to fields or methods is changed, just that additional methods are added.
Unless you're in the habit of writing method names that contain '$', I think it's unlikely that you'll directly call
these new methods, and if you do, it should be easy to spot! -
JSP Inner class generates IllegalAccess Error
I created an inner class inside of a JSP file. Unfortunately, Weblogic 5.1.0
compiles the inner class as private. So I got an IllegalAccessError. Is
there a way to use inner classes in JSP files?
Thank you.
- Remington
Here is my code:
<%
Object obj = new Object()
public int hashCode()
return 100;
out.println( "obj: " + obj.hashCode() );
%>
Error messages:
Wed Jan 31 17:23:38 PST 2001:<E> <ServletContext-General> Servlet failed
with Exception
java.lang.IllegalAccessError: try to access class
jsp_servlet/_test/_test01$1 from class jsp_servlet/_test/_test01
at jsp_servlet._test._test01._jspService(_test01.java:66)
at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
at
weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
:105)
at
weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
l.java:742)
at
weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
l.java:686)
at
weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContext
Manager.java:247)
at
weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:361)
at
weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:261)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java, Compiled
Code)
Works ok with sp8.
Remington Li <[email protected]> wrote:
> I created an inner class inside of a JSP file. Unfortunately, Weblogic 5.1.0
> compiles the inner class as private. So I got an IllegalAccessError. Is
> there a way to use inner classes in JSP files?
> Thank you.
> - Remington
> Here is my code:
> <%
> Object obj = new Object()
> {
> public int hashCode()
> {
> return 100;
> }
> };
> out.println( "obj: " + obj.hashCode() );
> %>
> Error messages:
> Wed Jan 31 17:23:38 PST 2001:<E> <ServletContext-General> Servlet failed
> with Exception
> java.lang.IllegalAccessError: try to access class
> jsp_servlet/_test/_test01$1 from class jsp_servlet/_test/_test01
> at jsp_servlet._test._test01._jspService(_test01.java:66)
> at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
> at
> weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
> :105)
> at
> weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
> l.java:742)
> at
> weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
> l.java:686)
> at
> weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContext
> Manager.java:247)
> at
> weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:361)
> at
> weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:261)
> at weblogic.kernel.ExecuteThread.run(ExecuteThread.java, Compiled
> Code)
Dimitri
-
I don't understand the design of inner class private member
This is a question about the java language specification of inner classes.
In the java langage specification document, we read
If 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 (�7.6)
that encloses the declaration of the member.
This allows following code :
public class PrivateTest {
public PrivateTest()
Hello hello = new Hello();
System.out.println(hello.secret);
class Hello
private String secret = "This is a secret";
} wherein accessing the private secret field is allowed
from into the PrivateTest enclosing class.
My questions are :
a) It seems that private methods or constructors of
inner classes have no meaning, we could also declare
them as public. True or false ?
b) Is there any reason that Java bypass this private
mechanism ?
c) Why is the above definition not written with
"first enclosing" instead of "top level" ?
Thanks in advancePrivate methods and constructors of an inner class can only be accessed within the outer class. Other classes can't instantiate it or use the private methods.
You can also make your inner class private, so it is not possible to refer to the class from outside (and thereby another way of preventing it from being instantiated).
So it does matter which access modifiers you use.
I think top level is more precise than first enclosing, because you can have inner classes in inner classes, which are still available for the top level class (haven't tested this). -
Private inner class and static private inner
Hi,
I understand the concept and usage of inner classes in general.
When should we go for a private inner class and when for a static private inner class? I tried searching but it wasn't of much help.
Basically I need to design a caching solution in which I need to timestamp the data object. After timestamping, data will be stored in a HashMap or some other collection. I'm planning to use a wrapper class (which is inner and private) which holds the data object and timestamp. I can make the program work by using either normal inner class or static inner class, however would like to know which is better in such case. Also If I can get some general guidelines as to when to use a staic inner class and when to use a normal inner class, it would help me.
Thanks in advance.user1995721 wrote:
When should we go for a private inner class and when for a static private inner class?
I can make the program work by using either normal inner class or static inner class, however would like to know which is better
If I can get some general guidelines as to when to use a static inner class and when to use a normal inner class, it would help me.Making the inner class static is helpful in that it limits visibility.
If the inner class needs to access non-static fields or methods from the containing class instance
the inner class has to be non-static. -
HELP: Cannot refer to non-final variable inside inner class
Below is a function that WAS working beautifully. I had to restructure many things in my code base to suit a major change and I have to make this function static. Since I made this function static, I get some errors which are displayed in comments next to the line of code.
Can anyone offer any advice how to fix this?
static private void patchSource( final Target target, final TargetResolver resolver, final TexSheetCommand args ) throws Exception
boolean bDone = false;
Element e;
SAXReader sax = new SAXReader();
FileInputStream fis = new FileInputStream( args.getInputFile() );
Document document = sax.read( fis );
Element root = document.getRootElement();
if( root.getName().equals( "Sheet" ) )
XMLParser.iterateElements( root, new XMLElementCallback()
public void onElement( Element element )
XMLParser.iterateAttributes( element, new XMLAttributeCallback()
public void onAttribute( Element element, Attribute attribute )
if( attribute.getName().equals( "guid" ) )
e = element; // PROBLEM: Cannot refer to a non-final variable e inside an inner class defined in a different method
// WARNING: Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator<Attribute>
for( Iterator<Attribute> it = element.attributeIterator(); it.hasNext(); )
Attribute a = (Attribute)it.next();
if( a.getName().equals( "randOffset" ) )
Integer i = new Integer( resolver.getTotalPermutations() );
a.setValue( i.toString() );
bDone = true; // PROBLEM: Cannot refer to a non-final variable bDone inside an inner class defined in a different method
if( ( !bDone ) && ( e != null ) )
Integer i = new Integer( resolver.getTotalPermutations() );
e.addAttribute( "randOffset", i.toString() );
FileOutputStream fileOut = new FileOutputStream( args.getInputFile() );
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter( fileOut, format );
xmlWriter.write( document );
fileOut.close();
}PS.) on a side note there is a warning on one of the lines too. Can anyone offer help on that one too?!
Thanks in advance.It is already set to that - it does look correct in Eclipse, honest.
It's just the block that's gone crazy with the formatting. I've spent around 10 minutes trying to tweak it just so it displays correctly but it wasn't making sense.
I'd rather not turn this conversation into a judgement of my code-style - I already understand that it doesn't conform to the 'Java way' and I've had Java programmers bash me about it for a long time. -
I'm trying to complete a "turn the lightbulb on and off" program, but when I try to draw circle2 in the
ButtonListener class I get an error message cannot find symbol. This is in reference to the Graphics
variable "page" created in the paintComponent method below. Shouldn't the inner class, private or
public inherit all data variables including objects from the parent class, in this case, the Bulb class? The code is below.
By the way, this IS NOT a school assignment so any help would be appreciated. I'm just trying to learn
this language.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Bulb extends JPanel
private JButton push;
private Circle circle, circle2;
private final int DIAMETER = 100;
private final int X = 10;
private final int Y = 10;
public Bulb()
circle = new Circle(DIAMETER, Color.white, X,Y);
circle2 = new Circle(DIAMETER, Color.yellow, X, Y); // to separate class
push = new JButton("Turn on the Bulb");
push.addActionListener(new ButtonListener());
add(push);
setPreferredSize(new Dimension(500, 500));
setBackground(Color.black);
public void paintComponent(Graphics page)
super.paintComponent(page);
circle.draw(page);
private class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent event) //PROBLEM AREA. I GET ERROR MESSAGE STATING
// "CANNOT FIND SYMBOL" IN REFERENCE TO VARIABLE "PAGE."
// I THOUGHT THE INNER CLASS INHERITS ALL DATA FROM
// PARENT CLASS SUCH AS "PAGE."
circle2.draw(page);
}There are fields, which are associated with either a class or an object (and thus live in the heap in an object on the heap), and there are local variables, which are associated with methods and threads (i.e., a method invoked within a thread, and which thus live on the stack).
They're not the same thing.
You can't use a local variable in your paintComponent method in a different method.
Anyway you're designing your class wrong. Think model-view-controller. You have the model: a bunch of state and possibly behavior that represents the thing being seen, modified, and displayed. You have the view, which is how you see the model. And you have the controller, which modifies the model.
Your event handlers are part of the controller. They should change the model.
Your paintComponent method is part of the view.
So the event handlers should change some data, e.g., add a note that a circle should be displayed.
Then your paintComponent method should look at the data and act accordingly -- e.g., see that there's a circle to be displayed, and display it. -
Help,about why we use inner class?
Hi,
when i read "java Tutorial"
i found there is one chapter about inner class .
i copy it down as follow.
the context is about there is a class Stack, and this class want to implement some function of interface Iterator,but as the book said
we should not let class Stack implement the Iterator directly, we should add a inner class inside the Stack .
i know it's very import ,but i still can not understand the reason why add a inner class here.
hope somebody can explain it a little more for me or give an example.
thank in advance!
Iterator defines the interface for stepping once through the elements within an ordered set in order. You use it like this:
while (hasNext()) {
next();
The Stack class itself should not implement the Iterator interface, because of certain limitations imposed by the API of the Iterator interface: two separate objects could not enumerate the items in the Stack concurrently, because there's no way of knowing who's calling the next method; the enumeration could not be restarted, because the Iterator interface doesn't have methods to support that; and the enumeration could be invoked only once, because the Iterator interface doesn't have methods for going back to the beginning. Instead, a helper class should do the work for Stack.
The helper class must have access to the Stack's elements and also must be able to access them directly because the Stack's public interface supports only LIFO access. This is where inner classes come in.
Here's a Stack implementation that defines a helper class, called StackIterator, for enumerating the stack's elements:
public class Stack {
private Object[] items;
//code for Stack's methods and constructors
not shown
public Iterator iterator() {
return new StackIterator();
class StackIterator implements Iterator {
int currentItem = items.size() - 1;
public boolean hasNext() {
public Object next() {
public void remove() {
or you can visit here
http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.htmlthe context is about there is a class Stack, and this
class want to implement some function of interface
Iterator,but as the book said
we should not let class Stack implement the Iterator
directly, we should add a inner class inside the
Stack .Simply because the implementation of the Iterator is nobody's business. By declaring it to be a private inner clss, nobody will ever know about it and only see the Iterator interface. -
Hello, I was just wondering if someone can help me understand inner classes a little. If I have the following code:
class Parent
private String myString = new String(�I am parent�);
public void writeIt()
System.out.println(myString);
public void displayIt()
System.out.println((new InnerParent()).readMyString());
class InnerParent
public String readMyString()
return myString;
class Child extends Parent
private String myString = new String(�I am child�);
public void writeIt()
System.out.println(myString);
If we execute the following lines on the code
Child myChild = new Child();
Parent myParent = new Parent();
myChild.writeIt();
myParent.writeIt();
myChild.displayIt();
myParent.displayIt();
Why does the following code display?
I am child
I am child
I am parent
I am parent
==
Thanks!Child myChild = new Child();
Parent myParent = new myChild();you again made a mistake,
it should be
Child myChild = new Child();
Parent myParent = new Child();
and now the output is
I am child
I am child
I am parent
I am parent
because, myChild.writeIt(); displays the stirng, I am child, straightforward, when it comes to myParent.writeIt(); it displays the string I am child because, myParent is of the type Child() which has been casted back to Parent, since child extends parent this can be done, and so, it just behaves as if it is a child, and so it displays I am child. when it comes to myChild.displayIt(), it uses the string in the Parent class, since it extends Parent and it does not override that method, it has to use that string ,and so it displays I am Parent, and similarly for the myParent.displayIt(), also it displays I am Parent. Hope you Understood now.
Maybe you are looking for
-
Std report reg. inventory side
hi all, we required all the details of GRN & MIRO including FI document with valuation. i.e (materil doc no,date, ref no, qty, materila, fi do no , valuation , pur inv no , ref no , date, net, gros amt, fi doc of miro etc.) hv any standred report in
-
Printing problem on Deskjet F2280 connected to JetDirect en3700 (Scanning works)
Hi, Recently acquired a JetDirect en3700 and after updating it to the latest firmware release (V.28.22.FF?) hooked up my trusty Deskjet F2280 to it. The printer is detected by the print server and I can scan pages using the Web UI but I can't print a
-
Digital Signatures and Email Encryption on iPhone
One of our clients has implemented a policy whereby all email communications with vendors must be digitally signed and encrypted. I know SSL allows the iPhone to create an encrypted connection to the email server. However, is there a way to actually
-
Display in "Oracle Forms 10g" a BLOB item
Hey, anybody know if there was any java component or a way to display in "Oracle Forms 10g" a BLOB item, which contains no images, but files of type PDF, DOC, TXT .... Thank you
-
Unusual 550 5.7.1 Command Not Allowed being sent from Exchange 2010
Greetings, I have an Exchange 2010 server that seems to be rejecting some emails from external domains with 550 5.7.1 Command Not Allowed. I've taken a look at the SMTP Receive logs (below) and can't seem to find any reason why the emails are getting