Declaring an object

I have a class (lets say it innerClass) which is nested inside the main. I have a method which has been used defined another class. Now, i want to create an object of the class which contains the method definition and use it in the innerClass which is inside main. How can i do it?
Heres a sample code:
Class A
method m()
some code;
public static void main(String [] args)
display.asyncExec(new Runnable() ) //Innerclass
want to use the method here;
Now where do i create and with what do i initialize it?
Edited by: iconabhi on Nov 30, 2007 8:51 PM

If it's not evident to you where and how your object should be constructed, you probably don't need an instance of that object. You should make the method static and call it statically, with A.m().
Now, if what you have is multiple classes (say A, B, C, D) implementing the same interface I, and m() is declared in I, then that's a different story. That's closer to the Strategy pattern that petes mentioned. However even with the strategy pattern, the whole point is that you would just have some object of type I supplied to you from the outside caller or a factory method. So it seems more likely that you just need a static method.

Similar Messages

  • So how do you declare an object?

    Okay I have a program I'm trying to build that lets me navigate between menus...
    Main Menu starts up:
    (Unimportant)
    Then it takes me to another Menu.
    When this is over I want to go back:
       System.out.println("Select: ");
            System.out.println("1: to Return to the main menu");
            System.out.println("or");
            System.out.println("0 to Exit");
         if(input.nextInt()==1){
             main(); // <-- error here
         else if(input.nextInt()==0){
             System.exit(0);
            }   It doesnt find the main method because I didn't declare it as an object at the top...
    How do I do that?
    Edited by: tark_theshark on Mar 30, 2008 5:24 AM

    Nah, this has nothing to do with declaring an object, and you really don't want to do this. What you really want to do is to have a loop of some kind, say a while loop and have the loop repeat until the user presses "0". Something like so:
        public static void main(String[] args)
            boolean done = false;
            while (!done)
                if(input.nextInt() == 0)
                    done = true;
        }Edited by: Encephalopathic on Mar 30, 2008 6:27 AM

  • Puzzle about declare List object

    Why we declare a object using "List list=new ArrayList();" other than "ArrayList list=new ArrayList();"?I have seen in Java API that:"Source source=new StreamSource();" other than "StreamSource souce=new StreamSource();".Is there any advantages to do this?

    just gives you more flexibility when you may possibly change the instance of the object being created.... more like the Factory patteren....
    hmmm.... i dont think im making much sence here.... :O)) let me explain with an example....
    the return type of Calendar.getInstance() is Calendar while internally it actually returns an instance of GregorianCalendar which is a sub-class of the Calendar class... the reason to that all the methods that you want are available in the Calendar class, & if a couple of version down the road if the API changes to return an instance of some other sub-class of Calendar, anyone using it would not be effected....
    BUT if in your case you are using specific methods that are only available in the ArrayList and not in the List class.... then you would be better off using ArrayList list=new ArrayList()....
    hope this explains to some extent
    regards
    omer

  • Where do I declare my objects?

    I've never understood where to instantiate/construct/declare? my objects. For example when making a JFrame I could put
    JFrame frame;
    at the top of the program and the in the main class put
    frame = new Frame();
    or I could just put
    JFrame frame = new JFrame();
    Which one do I use and in what situation?

    You could theoratically do both. Because it really depends on the scope of how you want to use your object.
    For example, for the following code... You can subsequently use the xxx Object in xxxMethod2()....
    public class NewClass {
         private Object xxx;
         public void xxxMethod() {
              xxx = new Object();
         public void xxxMethod2() {
    }But for the following code... you can't use xxx in xxxMethod2()... since the scope of the object already ends in xxxMethod().
    public class NewClass {
         public void xxxMethod() {
              Object xxx = new Object();
         public void xxxMethod2() {
    }I hope i've made it simple enough for you to understand.

  • Declarative java object cache in non oc4j container

    hello,
    i'm trying to use the cache.jar from 10g in a standalone application.
    i've followed the j2ee services guide and use cache.open(path_to_javacache.xml). javacache.xml has preload-file defined, in which i've declared my userdefined classloader and userdefined cached object. the implementations of both implement declarable. however,when i use cacheaccess.getaccess(region_name) i get regionnotfoundexception.
    i've also tried to use the configurator alternative, where i specify the declarative cache xml file. but this gives me a classcastexception.
    any suggestions. better yet is there a sample program that
    shows the use of a decl cache in a non oc4j container.
    thanks

    Hi,
    I ran into the same problem while evaluating OC4J V9 Java Cache standalone.
    Cache.open() silently ignores errors:
    * Cache.open(path_to_javacache.xml) seems to silently swallow alle error messages (in your case the ClassCastException) and the ignore the configuration file
    * so to get meaningful error messages, first attempt to open the file with new Configurator(path_to_javacache.xml)
    * once there are no more errors, you can open it with Cache.open(path_to_javacache.xml)
    Now, to get around the ClassCastException:
    * you need to add xmlparserv2.jar from your oc4j distribution
    * this must be the first xml-parser in your classpath (when e.g. xerces.jar comes first, you will get a ClassCastException)
    A relative javacache.xml is relative to your working directory.
    The preload-file - Path seems to be relative to the javacache.xml path, if it is not absolute. I keep javacache.xml and preload-file together which worked for me.
    Hope this help,
    Andreas

  • Declaring an object with a string

    Is there a way to declare a data object (at runtime) from a
    string descriptor? For example, lets say I load a text file that
    contains the following string: "{name:"bob", age:42,
    location:"earth"}". Is there a way to then have Flash parse the
    string and interpret it as an Object object in memory?
    Thanks!

    This may be just what I need, thanks for the tip!
    I've set up a quick test though, and I'm having some
    problems. My code is as follows:
    import JSON;
    var str:String = "{'var1':'hello world'}";
    var obj:Object = JSON.parse(str);
    trace(obj.var1);
    All that I'm getting is an "[object Object]" trace in my
    output window (upon JSON.parse() calling). Scripts following the
    parse command do not run (ie: the trace action). And, if I try to
    access the obj object later (I was checking it upon a button
    press), then Flash is reporting that obj is undefined. Do you have
    any insight on this?
    Thanks for your help!!

  • Help, can I declare an object using a variable name

    I need to make a bunch of objects using a for loop, so I was wanting to name the object one of the variables that I read. But I basically want to know if I can do this.
         private Software makeObject(String proName, int proStock, double proPrice,String objName){
              Software objName = new Software(proName,proStock,proPrice);
              return objName;
    I want to create a Software object using the objName inputted to it. The software object holds three fields as you can see. The name, num in stock, and price. However it won't let me do this, because it says objName is a duplicate variable. Help would be appreciated

    private Software makeObject(String proName, int proStock, double proPrice,String objName){
    Software objName = new Software(proName,proStock,proPrice);
    ... it won't let me do this, because it
    says objName is a duplicate variable. Help would be
    appreciatedWell, it is duplicate. Change the name of one or the other of those variable names.

  • Function module parameters declare BOR Object

    I dont know if this is even logical...
    I need to create a function module which will be used in my  program..
    Can I create an object of BOR object type say 'Sales Order'  and pass it as an export parameter in Function Module..
    i.e i will pass the obj key and obj type as import..
    I want to instantiate that Sales Order.. and pass the whole Sales oRder as export/tables  parameter..
    I know swc_object_create is supposed to create an object but as i can see it only has the handle.. and it is of type swc_object..
    But i want to export  the whole Instance .. so that i can call the methods of the object  in my original program..
    Regards,
    krishna

    Hi Ravi ,
    I simplified my requirement but my actual requirement is with workflows...
    I have a scenario in workflow where,
    1.Activity step to fill internal table with sales order numbers
    2.loop at sales order numbers internal table
    3.Activity Step to Instantiate  based on order numbers
    4. Activity Step to Edit these sales orders
    5.end the loop
    For the above logic in workflows i have separate Activity step for instantiation..What I am thinking of is to instantiate the sales orders and fill the instances in the internal table in Step 1 instead of just order numbers..In the BOR method/F.M  of Step 1 I need to export the Instance of the Sales Orders (this is my actual question/problem, how do i instantiate while coding??swc_object_create, creates only a ref to object ...If I am able to create the object what should the type be in export /tables parameter)
    This way i can remove the loop and offer parallel processing (from miscellaneous tab in activity step) and send multiple Edit workitems to user  at Once instead of one after the other..
    Please let me also know how you would handle the above situation, i am very new to workflows and BOR.

  • Declaring String object

    Is it a good practice to initialize a String object variable to a zero length string?
    String strMyString = "";and later, when we need to assign a new value for it, we just do
    strMyString = "Hello World";This is correct or not?

    It's only appropriate if you want an empty string to be the default, and you don't invariably reassign it. This doesn't happen very often; usually you either can (and should) unambiguously find a value for it, or you can just use null, or you don't need a default at all.

  • Declaring MovieClipLoader Objects in loop

    I'm trying to clean up my code. I have a varying number of
    MovieClipLoaders and related listeners.
    I wanted to make a general purpose loop to create them where
    I can call the function with a variable and instantiate both the
    MovieClipLoader and its listener.
    I'm starting with pretty typical MovieClipLoader code.
    var MCname = new MovieClipLoader();
    var MCListener = MCSlotname+"Listener";
    var MCListener:Object = new Object();
    MCSlotname.addListener(MCListener);
    //Load Files
    MCListener.onLoadComplete = function(MCSlotname:MovieClip) {
    _global.MCname.Loaded = true;
    But if I try to put it into a function and pass a variable so
    that each call to the function will instantiate a different
    movieclip loader it seems I run into a problem.
    function MakeLoader(InstanceName){
    var MCname = new MovieClipLoader();
    How do I use the value of the instanceName to provide a
    unique var name for the instancing of the new MovieClipLoader?
    Thanks.

    > var MCListener = MCSlotname+"Listener";
    > var MCListener:Object = new Object();
    That won't do what I imagine you want it to do. The first
    line gets overwritten by the second line.
    > How do I use the value of the instanceName to provide a
    unique var name for
    > the instancing of the new MovieClipLoader?
    There are a couple of different ways this could be
    approached. The most literal answer to your question I think would
    be:
    this['loader_'+instanceName] = new MovieClipLoader();
    So, say the instance name is "myClipOne", it would make:
    this.listener_myClipOne
    However, here are a couple other things to consider:
    1) A single MovieClipLoader can load multiple clips at once.
    2) Neither the MovieClipLoader nor the listener need to be
    assigned to a variable, or unique variable. They will function the
    same wether or not there is a reference to them in variable.

  • Question on declaring an object initialized in a constructor

    Anyone knwo what is wrong with the winappFrame line below? It's from a book I'm following along and it errors in my IDE.
    public class winapp extends java.applet.Applet {
         public static void main(String[] args) {
              winappFrame frame = new winappFrame("System Status");
              frame.resize(400, 300);
              winapp applet = new winapp();
              frame.add("Center", applet);
              applet.init();
              applet.start();
              frame.show();
         public void paint(Graphics g) {
              g.drawString("The system is currently down", 60, 30);
         class winappFrame extends Frame {
              public winappFrame(String str) {
                   super (str);
              public boolean handleEvent(Event evt) {
                   switch(evt.id) {
                        case Event.WINDOW_DESTROY:
                             dispose();
                        System.exit(0);
                        return true;
                        default:
                        return super.handleEvent(evt);
         }

    Your error message in Reply #2 (don't know why it says textfields, but ...) means:
    winappFrame class only exists inside an instance of winapp. So, try this:
    Instead of what you have:
    winappFrame frame = new winappFrame("System Status"); // 1
    frame.resize(400, 300); // 2
    winapp applet = new winapp(); // 3Do this:
    winapp applet = new winapp(); // 3 [above]
    winappFrame frame = applet.new winappFrame("System Status"); // 1 above [note change]
    frame.resize(400, 300); // 2 [above]

  • Declare object type inside the package

    Hi,
    How can I declare an object type inside the package?
    CREATE TYPE TempObj AS OBJECT (
    user_id number,
    text varchar2(4000),
    date_created DATE
    This will not work if placed inside this:
    CREATE OR REPLACE PACKAGE SAMPLE_PKG IS
    ---declaration goes here.
    END SAMPLE_PKG;
    I tried using the type RECORD and it worked. But I am just curious how to declare an Object. Or maybe RECORD is the replacement of Object? is this correct?
    thanks,
    Baldwin

    The inside of a PL/SQL package should contain PL/SQL statements.
    CREATE TYPE is not a PL/SQL statement. You can't create a table in package either.
    If data protection is the reason that you would rather create the type inside the package, then consider using a record type as you suggested, or hiding the SQL type in a more protected schema.
    Message was edited by:
    jonjac

  • Difference b/w DATA TYPE and DATA OBJECT & differences b/w TYPE and LIKE

    hai
    can any one say the differences between Data type and Data Object.
    And also differences between TYPE and LIKE
    thanks
    Gani

    hi,
    _Data Types and Data Objects_
          Programs work with local program data – that is, with byte sequences in the working memory. Byte sequences that belong together are called fields and are characterized by a length, an identity (name), and – as a further attribute – by a data type. All programming languages have a concept that describes how the contents of a field are interpreted according to the data type.
          In the ABAP type concept, fields are called data objects. Each data object is thus an instance of an abstract data type. There are separate name spaces for data objects and data types. This means that a name can be the name of a data object as well as the name of a data type simultaneously.
    Data Types
       As well as occurring as attributes of a data object, data types can also be defined independently. You can then use them later on in conjunction with a data object. The definition of a user-defined data type is based on a set of predefined elementary data types. You can define data types either locally in the declaration part of a program using the TYPESstatement) or globally in the ABAP Dictionary. You can use your own data types to declare data objects or to check the types of parameters in generic operations.
         All programming languages distinguish between various types of data with various uses, such as ….. type data for storing or displaying values and numerical data for calculations. The attributes in question are described using data types. You can define, for example, how data is stored in the repository, and how the ABAP statements work with the data.
    Data types can be divided into elementary, reference, and complex types.
    a. Elementary Types
    These are data types of fixed or variable length that are not made up of other types.
    The difference between variable length data types and fixed length data types is that the length and the memory space required by data objects of variable length data types can change dynamically during runtime, and that these data types cannot be defined irreversibly while the data object is being declared.
    Predefined and User-Defined Elementary Data Types
    You can also define your own elementary data types in ABAP using the TYPES statement. You base these on the predefined data types. This determines all of the technical attributes of the new data type. For example, you could define a data type P_2 with two decimal places, based on the predefined data type P. You could then use this new type in your data declarations.
    b.  Reference Types
    Reference types are deep data types that describe reference variables, that is, data objects that contain references. A reference variable can be defined as a component of a complex data object such as a structure or internal table as well as a single field.
    c. Complex Data Types
    Complex data types are made up of other data types. A distinction is made here between structured types and table types.
    Data Objects
          Data objects are the physical units with which ABAP statements work at runtime. The contents of a data object occupy memory space in the program. ABAP statements access these contents by addressing the name of the data object and interpret them according to the data type.. For example, statements can write the contents of data objects in lists or in the database, they can pass them to and receive them from routines, they can change them by assigning new values, and they can compare them in logical expressions.
           Each ABAP data object has a set of technical attributes, which are fully defined at all times when an ABAP program is running (field length, number of decimal places, and data type). You declare data objects either statically in the declaration part of an ABAP program (the most important statement for this is DATA), or dynamically at runtime (for example, when you call procedures). As well as fields in the memory area of the program, the program also treats literals like data objects.
            A data object is a part of the repository whose content can be addressed and interpreted by the program. All data objects must be declared in the ABAP program and are not persistent, meaning that they only exist while the program is being executed. Before you can process persistent data (such as data from a database table or from a sequential file), you must read it into data objects first. Conversely, if you want to retain the contents of a data object beyond the end of the program, you must save it in a persistent form.
    Declaring Data Objects
          Apart from the interface parameters of procedures, you declare all of the data objects in an ABAP program or procedure in its declaration part. These declarative statements establish the data type of the object, along with any missing technical attributes. This takes place before the program is actually executed. The technical attributes can then be queried while the program is running.
         The interface parameters of procedures are generated as local data objects, but only when the procedure is actually called. You can define the technical attributes of the interface parameters in the procedure itself. If you do not, they adopt the attributes of the parameters from which they receive their values.
    ABAP contains the following kinds of data objects:
    a.  Literals
    Literals are not created by declarative statements. Instead, they exist in the program source code. Like all data objects, they have fixed technical attributes (field length, number of decimal places, data type), but no name. They are therefore referred to as unnamed data objects.
    b.  Named Data Objects
    Data objects that have a name that you can use to address the ABAP program are known as named objects. These can be objects of various types, including text symbols, variables and constants.
    Text symbols are pointers to texts in the text pool of the ABAP program. When the program starts, the corresponding data objects are generated from the texts stored in the text pool. They can be addressed using the name of the text symbol.
    Variables are data objects whose contents can be changed using ABAP statements. You declare variables using the DATA, CLASS-DATA, STATICS, PARAMETERS, SELECT-OPTIONS, and RANGESstatements.
    Constants are data objects whose contents cannot be changed. You declare constants using the CONSTANTSstatement.
    c.  Anonymous Data  Objects
    Data objects that cannot be addressed using a name are known as anonymous data objects. They are created using the CREATE DATAstatement and can be addressed using reference variables.
    d.  System-Defined Data Objects
    System-defined data objects do not have to be declared explicitly - they are always available at runtime.
    e.  Interface Work Areas
    Interface work areas are special variables that serve as interfaces between programs, screens, and logical databases. You declare interface work areas using the TABLES and NODESstatements.
    What is the difference between Type and Like?
    Answer1:
    TYPE, you assign datatype directly to the data object while declaring.
    LIKE,you assign the datatype of another object to the declaring data object. The datatype is referenced indirectly.
    Answer2:
    Type is a keyword used to refer to a data type whereas Like is a keyword used to copy the existing properties of already existing data object.
    Answer3:
    type refers the existing data type
    like refers the existing data object
    reward if useful
    thanks and regards
    suma sailaja pvn

  • How to use methods when objects stored in a linked list?

    Hi friend:
    I stored a series of objects of certain class inside a linked list. When I get one of them out of the list, I want to use the instance method associated with this object. However, the complier only allow me to treat this object as general object, ( of Object Class), as a result I can't use instance methods which are associated with this object. Can someone tell me how to use the methods associated with the objects which are stored inside a linked list?
    Here is my code:
    import java.util.*;
    public class QueueW
         LinkedList qList;
         public QueueW(Collection s) //Constructor of QuequW Class
              qList = new LinkedList(s); //Declare an object linked list
         public void addWaiting(WaitingList w)
         boolean result = qList.isEmpty(); //true if list contains no elements
              if (result)
              qList.addFirst(w);
              else
              qList.add(w);
         public int printCid()
         Object d = qList.getFirst(); // the complier doesn't allow me to treat d as a object of waitingList class
              int n = d.getCid(); // so I use "Object d"
         return n; // yet object can't use getCid() method, so I got error in "int n = d.getCid()"
         public void removeWaiting(WaitingList w)
         qList.removeFirst();
    class WaitingList
    int cusmNo;
    String cusmName;
    int cid;
    private static int id_count = 0;
         /* constructor */
         public WaitingList(int c, String cN)
         cusmNo = c;
         cusmName = cN;
         cid = ++id_count;
         public int getCid() //this is the method I want to use
         return cid;

    Use casting. In other words, cat the object taken from the collection to the correct type and call your method.
       HashMap map = /* ... */;
       map.put(someKey, myObject);
       ((MyClass)(map.get(someKey)).myMethod();Chuck

  • Multiple instantiations of the same object

    Can someone please explain to me the difference of these two circumstances upon the JVM:
    1) I declare an object outside the loop and instantiate a new object on each iteration of the loop
    Object obj = null;
    for (int i = 0; i < 6; i++) {
        obj = new Object();
    }2) I declare and instantiate the object inside the loop only
    for (int i = 0; i < 6; i++) {
        Object obj = new Object();
    }I assume in the first example that I am reserving memory space and overwriting it on each iteration, whereas in the second example I am reserving and consuming a new memory space on each iteration.
    If that assumption is correct, which is the more efficient? Wouldn't option 1 be easier on garbage collection?

    I compiled both cases using Sun javac (1.4.1) and used javap to view the compiled code. It looks the same to me. Here's the compiled code (for the loop) for the first case   2 iconst_0
       3 istore_2
       4 goto 18
       7 new #2 <Class java.lang.Object>
      10 dup
      11 invokespecial #1 <Method java.lang.Object()>
      14 astore_1
      15 iinc 2 1
      18 iload_2
      19 bipush 6
      21 if_icmplt 7
      24 returnHere's the compiled code the second case   0 iconst_0
       1 istore_1
       2 goto 16
       5 new #2 <Class java.lang.Object>
       8 dup
       9 invokespecial #1 <Method java.lang.Object()>
      12 astore_2
      13 iinc 1 1
      16 iload_1
      17 bipush 6
      19 if_icmplt 5
      22 return

Maybe you are looking for

  • Delete dot (...) in report painter

    Hi, I created cost center report on report painter (GRR2). And as attached, some dot (...) is remained in column text and cannot delete. It seems just text, but cannot be deleted. DO you have any idea what is it? Yoshi

  • How to fix exclamation mark problem

    Basically since I updated to iTunes 11 and I went to make a new cd to listen to in the car a lot of my songs have got an exclamation mark next to them and says it can't find the original file so since I HATE the new iTunes i decided to downgrade back

  • How do I import text into the Keynote Titile

    I am trying to use the Keynote title in FCPX - I have "imported" the title over the picture image clip that I want to use, and that works fine, but I am having extreme difficulty in changing the text in the boxes that appear from ex TITILE to what te

  • Confirmation and consumption of milestone and its prceedings

    Example: Operation - Control key definition 0010  - Confirmation not possible 0020  - Confirmation possible,not neccessary 0030  - Milestone confirmation 0040  - Confirmation possible,not neccessary 0050  - Confirmation required While i do confirm th

  • My spell checker stopped working. How can I restore it?

    I tried to find in Tools - Options - Advanced how to turn it on and off, but I cannot find it. How to make it work? Restarting Thunderbird used to help, but not anymore. All words are highlighted as misspelled.