Inner classes help

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.

Similar Messages

  • 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.

  • Error in running jsp file which contains inner class,help !

    Environment ias sp4 for windows2000
    Error:
    try to access class jsp.APPS.bsteelWZ.order.OrderMgmtMain$1$sOrderHelper
    from class jsp.APPS.bsteelWZ.order.OrderMgmtMain
    OrderMgmt.jsp contains a class named sOrderHelper.
    It's all ok on ias sp2 for solaris.
    Thank you!

    405 errors in the HTTP cycle
    Any client goes through the following cycle:
    * Obtain an IP address from the IP name of your site (your site URL without the leading 'http://'). This lookup (conversion of IP name to IP address) is provided by domain name servers (DNSs).
    * Open an IP socket connection to that IP address.
    * Write an HTTP data stream through that socket.
    * Receive an HTTP data stream back from your Web server in response. This data stream contains status codes whose values are determined by the HTTP protocol. Parse this data stream for status codes and other useful information.
    This error occurs in the final step above when the client receives an HTTP status code that it recognises as '405'.
    Resolving 405 errors - general
    405 errors often arise with the POST method. You may be trying to introduce some kind of input form on your Web site, but not all ISPs allow the POST method necessary to process the form.
    All 405 errors can be traced to configuration of the Web server and security governing access to the content of the Web site.

  • 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • 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.html

    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 .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.

  • Need Help in Inner Classes

    Hi
    I joined as a faculty last week in an institution. To take class I need some information about inner classes in java.
    Basically i need where we use this concept in real time application. Now it is used by the developer or not? Moreover how it is working in java?
    Please somebody help me out...
    thanks in advance
    Chithrakumar

    I once wrote the following example class showing a bit of inner classes"public class Star {
         private String name;
         public Star(String name) { this.name= name; }
         public class Planet {
              private String name;
              public Planet(String name) { this.name= name; }
              public class Moon {
                   private String name;
                   public Moon(String name) { this.name= name; }
                   public String toString() { return name+" (orbiting "+Planet.this+")"; }
              public String toString() { return name+" (orbiting "+Star.this+")"; }
         public String toString() { return name; }
         public static void main(String[] args) {
              System.out.println(new Star("sun").new Planet("earth").new Moon("moon"));
    }Study it, run it and see if you understand what this is all about.
    kind regards,
    Jos

  • Please need help with Inner Classes

    Hi! I have the following inner class, but it is not an "explicit" inner class:
    import java.util.*;
    public class EXTERIOR_NOEXPLICITA {
         private Vector i;
         public void llena_Vector(int a){
              i = new Vector();
              for(int z=0;z<=a;z++)
                   i.addElement(""+z);
         public Enumeration test() {
              return new Enumeration(){
                   int item = i.size()-1;
                   public boolean hasMoreElements(){
                        return(item >= 0);
                   public Object nextElement(){
                        if(!hasMoreElements())
                             throw new NoSuchElementException();
                        else
                             return i.elementAt(item--);
    My question is, how can I put it in an explicyt inner class?
    Plese help me! =)
    Raul

    I am not entirely sure what you mean by explicit inner class. If you mean converting your anonymous class into a nested class, then it is quite easy:
    import java.util.*;
    public class EXTERIOR_NOEXPLICITA {
      private Vector i;
      public void llena_Vector(int a) {
        i = new Vector();
        for (int z = 0; z <= a; z++)
          i.addElement("" + z);
      private final class MyEnumeration implements Enumeration {
        int item = i.size() - 1;
        public boolean hasMoreElements() {
          return (item >= 0);
        public Object nextElement() {
          if (!hasMoreElements())
            throw new NoSuchElementException();
          else
            return i.elementAt(item--);
      public Enumeration test() {
        return new MyEnumeration();

  • 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?

  • Help! - JRE can't find classes that use inner classes!

    Whenever I try to launch an app using the JRE, if the class was built with an inner class definition, the JRE says it can't find the class.
    For instance:
    I created a class called GUI, which contains anonymous inner class definitions for the button handlers: addActionListener(new ActionListener()){, etc. 
    When I compile this class I get GUI.class and GUI$1.class
    When I try to launch this using the JRE:
    jre -cp c:\progra~1\myApps GUI
    The JRE spits out
    'Class not found: GUI'
    BUT if I go back and remove the action handlers so that the only compiled class file is GUI.class (not GUI$1.class) then the JRE can find the class no problem.
    What in the good Lord's name is going on here?

    Thanks for the response. Got the 1.2.2 version of the JRE, where I guess you no longer invoke jre.exe (no such file exists) but java.exe instead (not well documented).
    Also, the newer version of the JRE has no problems locating classes, so I guess I'm OK.

  • 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.

  • Adapters vs anonymous inner class (please help)

    I am trying to clean up my code by using anonymous inner classes to handle some action events. My code looks like this but I get an error
    Button.addActionListener(new MyClass() {
    public void actionPerformed(ActionEvent e) {
    my_Button_actionPerformed(e);
    it says that it cant find MyClass, but I thought I dont need to define it becaue I am defining it here, isnt that the point of a anonymous inner class

    yourBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
    });(BTW: use code tags in posting!)

  • 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.

  • Problem with Outer and Inner Classes....or better way?

    Right now I'm trying to create an Inner class.
    My .java file compiles ok, and I create my jar file too.
    But when I try to instantiate the Inner class, it fails:
    java.lang.NoClassDefFoundError: com/myco/vlXML/vlXML$vlDocument.
    Here's the class code:
    public class vlXML{
        private ArrayList myDocList=new ArrayList(); //holds documents
        public vlXML(){
        private class vlDocument{
            public vlDocument(){
            //stuff goes here
        public vlDocument vlDOC(){
            return new vlDocument();
        public void addDocument(){
            vlXML xxx=new vlXML();
            vlDocument myDoc=xxx.vlDOC();
            myDocList.add(myDoc);
        public int getNumDocs(){
            return myDocList.size();
    }Then, from a jsp page, I call:
    vlXML junk1=new vlXML();
    junk1.addDocument();...and get the error...
    Can someone help me figure out why it's failing?
    Thanks....

    You nailed it - thanks....(duh!)
    While I have your attention, if you don't mind, I have another question.
    I'm creating a Class (outer) that allows my users to write a specific XML file (according to my own schema).
    Within the XML file, they can have multiple instances of certain tags, like "Document". "Document"s can have multiple fields.
    Since I don't know how many "Documents" they may want, I was planning on using an Inner Class of "Document", and then simply letting them "add" as many as necessary (thus the original code posted here).
    Does that seem like an efficient (logical/reasonable) methodology,
    or is there there something better?
    Thanks Again...

  • Passing Inner class name as parameter

    Hi,
    How i can pass inner class name as parameter which is used to create object of inner class in the receiving method (class.formane(className))
    Hope somebody can help me.
    Thanks in advance.
    Prem

    No, because an inner class can never have a constructor that doesn't take any arguments.
    Without going through reflection, you always need an instance of the outer class to instantiate the inner class. Internally this instance is passed as a parameter to the inner class's constructor. So to create an instance of an inner class through reflection you need to get the appropriate constructor and call its newInstance method. Here's a complete example:import java.lang.reflect.Constructor;
    class Outer {
        class Inner {
        public static void main(String[] args) throws Exception{
            Class c = Class.forName("Outer$Inner");
            Constructor cnstrctr = c.getDeclaredConstructor(new Class[] {Outer.class});
            Outer o = new Outer();
            Inner i = (Inner) cnstrctr.newInstance(new Object[]{o});
            System.out.println(i);
    }

  • 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();
    }

Maybe you are looking for