.How to instantiate the innerclass from another class with coded eg.

How to instantiate the innerclass from another class(both for static & non static) please give me an eg with coding.

It's just a preference, but I like writing factory methods:
public class Outer {
    public class Inner {}
    public static class StaticInner {}
    public Inner innerInstance() {
        return new Inner();
    public static StaticInner staticInnerInstance() {
        return new StaticInner();
    public static void main(String[] args) {
        Outer.StaticInner si = Outer.staticInnerInstance();
        Outer outer = new Outer();
        Outer.Inner i = outer.innerInstance();
}Often, for me, the inner class implements an interface, and the factory method
lets you hide the implementation class:
public class Outer {
    private class Inner implements Runnable {
        public void run() {}
    public Runnable runnerInstance() {
        return new Inner();
    public static void main(String[] args) {
        Outer outer = new Outer();
        Runnable r = outer.runnerInstance();
}

Similar Messages

  • How to call a method from another class

    I have a problem were i have to call a method from another class. What is the command line that i have to use. Thanks.

    Here's one I wipped up in 10 minutes... Cool!
    package forums;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import krc.utilz.io.Filez;
    import java.io.FileNotFoundException;
    class FileDisplayer extends JFrame
      private static final long serialVersionUID = 0L;
      FileDisplayer(String filename) {
        super(filename);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(600, 800);
        JTextArea text = new JTextArea();
        try {
          text.setText(Filez.read(filename));
        } catch (FileNotFoundException e) {
          text.setText(e.toString());
        this.add(text);
      public static void main(String args[]) {
        final String filename = (args.length>0 ? args[0] : "C:/Java/home/src/forums/FileDisplayer.java");
        try {
          java.awt.EventQueue.invokeLater(
            new Runnable() {
              public void run() {
                new FileDisplayer(filename).setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
    Filez.read
       * reads the given file into one big string
       * @param String filename - the name of the file to read
       * @return the contents filename
      public static String read(String filename) throws FileNotFoundException {
        return Filez.read(new FileReader(filename));
       * Reads the contents of the given reader into one big string, and closes the reader.
       * @param java.io.Reader reader - a subclass of Reader to read from.
       * @return the whole contents of the given reader.
      public static String read(Reader in) {
        try {
          StringBuffer out = new StringBuffer();
          try {
            char[] bfr = new char[BFRSIZE];
            int n = 0;
            while( (n=in.read(bfr,0,BFRSIZE)) > 0 ) {
              out.append(bfr,0,n);
          } finally {
            if(in!=null)in.close();
          return out.toString();
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
      }Edited by: corlettk on Dec 16, 2007 1:01 PM - dang [code [/tags][                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How do I access data from another class?

    I have a class RailNetwork which extends Datastore. DataStore contains a vector filelines which I need to access from RailNetwork. How do I do this? What do I put infront of filelines.get(i); ?
    public abstract class DataStore
    {    Vector<String> fileLines = new Vector<String>(); }
    public class RailNetwork extends DataStore
    {    ...main(){ .......filelines.get(i);....... }
    }

    This is the code from RailNetwork class:
    public static void main(String[] args) {
              String templine;
              int i = 0;
              int vectorlength = super.filelines.size();
              for( i = 0 ; i < vectorlength ; i++ )
                   templine = (String) super.filelines.get(i);
                   setStations(templine);  }The errors (for both lines, only 1 shown):
    RailNetwork.java:49: non-static variable super cannot be referenced from a static context
                            templine = (String) super.filelines.get(i);
                                                ^
    RailNetwork.java:49: cannot find symbol
    symbol  : variable filelines
    location: class DataStore
                            templine = (String) super.filelines.get(i);
                                                     ^

  • Variable type Hierarchy, how to get the value from another similar variable

    Hi.
    We have created a variable, type hierarchy (using ORGEH hierarchy in HR based on 0ORGUNIT). Let's call this VAR1. We want to fill this with an User Exit, beacuse we want VAR1 to have the value from another variable, VAR2, which is also type hierarchy (and based on the same characteristic).
    However, when we program this user exit and use the VAR1 afterwards, it just behaves as if we have a single characteristic value and not a node value. As a result, we just get posts which do have the 'parent itself' as characteristic value, and none of the subnodes...  Any hints as to what we can do in our User exit to get the value passed over from VAR2 to VAR1 as a node value? Is there any spesific syntax to be used here that we are missing? ( The VAR1 and VAR2 are both defined as hierarchy variables, we have double checked...).

    Hi,
    are you on BI7.0? There you can create variables type replacement path and get the value out from a different variable without any coding.
    regards
    Cornelia

  • How to instantiate an object from another's class?

    Hi... first post here
    I have the following problem:
    I have a first object, lets call it obj1, of class X (where X could be, for example, 'Class1' or in another moment 'Class2', etc.)
    Now, I have another object, obj2, which I wish to instantiate it with the same class as obj1. The problem is I don't always know which class does obj1 belongs, so programming with an if-else statement and the getClass().getName() method is not a solution, since I cannot program for all the possible cases.
    I know that with obj1.getClass() I get obj1's class and that with obj1.getClass().getName() I get a String with obj1's class name.
    I guess that making obj2 of class Object I can get it, but my question is:
    How do I do to create the instance of obj2 so its class in that moment is the same as the class of obj1? (And by the way, how can I use a specific constructor of obj1 for obj2?)
    I repeat that the if-else method won't do since the class for obj1 won't always be in a known set of classes.
    Thanks for any help or tip you can give me
    Javier
    from Mexico

    You would use the Class.forName() static method to get a Class object of the class you are looking for. Then you would use its newInstance() to create an instance of that class using a no-arguments constructor. If you need some other constructor (and how would you know that?) then Class has a getConstructor(...) method and a getConstructors() method that return one or more Constructor objects you could use. Follow the API documentation from there.

  • Accessing display object on the stage from another class

    I've googled this to no avail, I've only found how to manipulate the stage itself and not a display object on it, and I'm noob enough to not be able to figure it out from there. :/
    I have a movie clip on the main timeline with instance name displayName. I created a button that should change what frame displayName goes to (in order to...did you guess it?! diplay the Name of the button. Awesome. )
    So I am trying to write the code in a reusable fashion and have the buttons all linked to a class called GeoPuzzle. Inside GeoPuzzle I instantiate a touch event and run the code. However, the function has to be able to change displayName in the main part of the timeline and, of course, the compiler says displayName doesn't exist because I'm in a class and I'm talking about the stage.
    Here is the simplified code in the class:
    package  com.freerangeeggheads.puzzleography {
        import flash.display.MovieClip;
        import flash.events.TouchEvent;
        public class GeoPuzzle extends MovieClip {
            //declare variables
            public function setInitial (abbrev:String, fullName:String, isLocked:Boolean):void {
                //set parameters
                this.addEventListener(TouchEvent.TOUCH_BEGIN, geoTouchBeginHandler);
            public function GeoPuzzle (): void {
            public function geoTouchBeginHandler (e:TouchEvent): void {
                   e.target.addEventListener(TouchEvent.TOUCH_END, geoTouchEndHandler);
                   //some other methods
                   nameDisplay.gotoAndStop(e.target.abbrev);
            public function geoTouchEndHandler (e:TouchEvent): void {
                //some other methods
               nameDisplay.gotoAndStop("USA");
    The lines in bold are my problem. Now this code doesn't actually execute as is so if you see an error in it, yeah, I have no idea what the problem is, but it DID execute before and these lines still gave me trouble so I'm trying to troubleshoot on multiple fronts.
    How can I tell displayName to change it's current frame from within display object class?
    Thanks!

    if displayName is a GeoPuzzle instance, use:
    package  com.freerangeeggheads.puzzleography {
        import flash.display.MovieClip;
        import flash.events.TouchEvent;
        public class GeoPuzzle extends MovieClip {
            //declare variables
            public function setInitial (abbrev:String, fullName:String, isLocked:Boolean):void {
                //set parameters
                this.addEventListener(TouchEvent.TOUCH_BEGIN, geoTouchBeginHandler);
            public function GeoPuzzle (): void {
            public function geoTouchBeginHandler (e:TouchEvent): void {
                   e.target.addEventListener(TouchEvent.TOUCH_END, geoTouchEndHandler);
                   //some other methods
                   this.gotoAndStop(this.abbrev);
            public function geoTouchEndHandler (e:TouchEvent): void {
                //some other methods
               this.gotoAndStop("USA");

  • How to get the value from another report Customizes Form

    Dear all,
    I create a report such as
    select * from mytable.table1
    where field1 = :bind_variable
    I create a menu to run this Customized Form and user have to select the bind_variable values. So I have another report created which also want this bind_variable as it WHERE Clause. But I don't want my user to key the same bind variable twice. They can just same the Customized Form and run for both report.
    Could anybody know how to get the bind_variable on 1st report and used by the 2nd report.
    Thank you very much.
    Best Rgds,
    SL Voon

    Hi,
    are you on BI7.0? There you can create variables type replacement path and get the value out from a different variable without any coding.
    regards
    Cornelia

  • How to reatch the maintimeline from a class

    Hi
    I have a project where I have attached i class to a movieclip
    I want to send a variable from the class to the maintimeline. I
    have done this in a project whith a document class then I used a
    function in the maintimeline and caled this from my class like:
    this.myfunctionintimeline(thevirabletosend);
    but how do a acheaved the same in this case?
    I have tryed:
    root.thenameofthefunction();

    Try: MovieClip(root).thenameofthefunction();

  • Instead of using session How to pass the variable from action class to JSP

    Im using Struts1.2 version.Created the Sample application to get the username.Upto action class im getting the username then i have to display the username in the JSP.Is there any options rather than using session variable to display the username.

    did you check the answer in your previous thread
    Passing Variable from Javascript to Controller

  • How to call a variable from another class?

    Greetings
    I�m designing a program that is called Senior.java, and I want to design it�s menus, for simplicity in reading the code, I want to write a separate java file for each menu. For example I want a file.java, edit.java etc�.
    Since I�m not a professional I�m having problems in calling the variable �bar�, that I created in senior.java,
    In Senior.java I have :
    JMenuBar bar = new JMenuBar();
    setJMenuBar( bar );
    In fileMenu.java I want to add file menu to the menu bar �bar�:
    bar.add( fileMenu );
    When I compile the fileMenu.java I got a �cannot resolve symbol � message, where symbol is the variable bar.
    Can you please help me, knowing that i'm using SDK1.4.1?

    Sun has recommendations for naming conventions. Class names should start with a capital letter. You should avoid using class names that are the same as classes provided in the SDK. Following these conventions will make it easier for people to help you. For example, you should not use file, nor should you use File. It's better to use MyFile, replacing My with something that makes sense to your application (SeniorFile?).
    Also, check the Formatting Help link when posting for a desciption on how to use the code tags for posting code.
    1. You need to establish references between your classes. One way is to have a constructor that has a JMenuBar argument.
    2. You can not add a file to a JMenuBar because a JMenuBar adds a JMenu. I don't think you want file to extend JMenu. It may be better for file to have a JMenu.
    I haven't tried to compile this code so no guarantees - just trying to show you an approach.
    public class Senior extends JFrame {
       public Senior() {
          JMenuBar bar = new JMenuBar();
          MyFile file = new MyFile(bar);
    //whatever else you need
    public class MyFile {
       public MyFile(JMenuBar mbar) {
          JMenu menu = new JMenu();
          mbar.add(menu);

  • How to get the data from a jtable with random order??

    hi everyone,
    i have a jtable i filled with Strring and Float data, i put this data to a MySQL database, and i use vectors and iterators to filled the database. the problem is there are some cells that are empty, and the Floats' columns throws me nullpointerexceptions.
    please if anyone know how to avoid that exception i'd would be great.
    thanks for your time.

    HI Siggi,
    Thank you for your reply..
    I am also planning to do FM to get the data. But it is saying that the Cluster table ZES does not exist (ZES is the the standard table, in SE11 also).
    How can I use the Fields from the that table.?
    What can I do now, can you please explain me about this point.
    Waiting for your reply.
    Thanks and Regards
    Rajesh
    Message was edited by:
            rajesh

  • How to reterive the attachments from a message with message id.

    Hi Friends,
    I want to know that How can i retrieve the attachments from an incoming message.
    Also how can I separate the body part from message. How can I get a list of files attached with a message.

    JavaMail API don't give really method to parse multipart message
    See http://www.jservlet.com/
    Object Pop3.Tools that will help you to parse a multipart message, get file attachment with specific file extension.
    regards,

  • How to assign a method from another class to dropDown processValueChange

    Hi
    Thank you for reading my post.
    in normal way we use same backing bean for methods of components and our pages.
    now i want to set the method that called after a dropDown value changed to another claas method.
    for example if my page name is
    messages.jsp and its backing bean is messages.java i want to set processValueChange of a dropDown box to class2.methodForDropDown...
    can some one please help me

    One approach will be to make your class a ivar of PageBean or SessionBean. That way you instantiate your class either in PageBean/SessionBean and PageBean or SessionBean as a parameter depending on the scope requirements of your class.
    Other approach which is eaiser would be to use the JSF API
    ValueBinding vb = FacesContext.getCurrentInstance().getApplication().
    createValueBinding("#{SessionBean1});
    SessionBean1 bean1 = vb.getValue(FacesContext.getCurrentInstance());
    The above code can be used anywhere within a JSF application to retrieve an object from any scope as long as the request has passed through the FacesServlet.
    No, you can't pass parameters to processValueChange.
    Hope this helps
    -Jayashri

  • XML reader and get the value from another class

    Hello to all, I have stupid question.
    I have main.java and ConfigXML.java(read my config xml file).
    Code from ConfigXML.java
    NodeList flnamelist = flcon.getElementsByTagName("filename");
    Element flnameEL= (Element)flnamelist.item(0);
    NodeList flnameTEXT = flnameEL.getChildNodes();
    String alsl = ((Node)flnameTEXT.item(0)).getNodeValue().trim();How I can get String alsl = ((Node)flnameTEXT.item(0)).getNodeValue().trim(); from my ConfigXML.java to main.java.
    Sorry for my bad english

    public class ConfigXML {
      private String alsl;
      // constructor goes here if necessary
      public void parse() {
        // something
        NodeList flnamelist = flcon.getElementsByTagName("filename");
        Element flnameEL= (Element)flnamelist.item(0);
        NodeList flnameTEXT = flnameEL.getChildNodes();
        alsl = ((Node)flnameTEXT.item(0)).getNodeValue().trim();
        // Notice that we assigned the data to an instance variable
      public String getAlsl() {
        return alsl;
    public class Main {
      // That's a really terrible name but at least let's capitalize it so it's standard
      public static void main(String[] args) {
        ConfigXML config = new ConfigXML();
        config.parse();
        String answer = config.getAlsl();
    }

  • How to invoke the compiler from another program

    Hi guys,
    Suppose I have a source code located in the file MyClass.java.
    Now suppose I'm running another program, and in this program I want to compile the MyClass.java file and create the MyClass.class file. Is there a way of doing it through the standard API?
    Thanks.

    I believe Java 1.6 has a Compiler class as a part of it's "standard" API. Before that, you've got a package called tools.jar in your SDK directory, which is a Java gateway to the compiler

Maybe you are looking for

  • I am unable to Save the "Note" field while Creation of new  Contact

    Hi , I  am unable to save the Note field while Creation of Contact in Web UI. Its happening in the Dev system but not in the QA Web UI. I have tried to debug  the component BP_CONT, But no use.  Can any one tell me the what could be the problem? Rega

  • Output printing from specific printer tray

    Hi, We have a printer with each tray containing different paper, in our case it is the color.  Based on the output we want to print, we want it to come out on a paper from a particular tray so that outputs of type X are on yellow, and type Y on pink

  • HT5534 How to fix error: An error occurred while installing the updates.(103)

    Unable to patch up to iwork 9.3 via Mac App Store

  • Where do we report bugs?

    We're all excited about the development of Flash Catalyst. It would be great if we could report bugs to help Adobe improve the quality and stability of the product. Here are some ideas: Create one thread for reporting all bugs, keep it at the top of

  • Iphone videos sent via mms are crap. Why?

    I want to know what the heck happened and who dropped the ball on iPhone video MMS. It gets compressed to the point where it is completely unable to be made out. Not to mention there is no zoom option. Maybe I could understand if you're sending a vid