Class instantiation

under what circumstances does one instantiate a class containing the main() method? i mean if one never needs to do it, then what's the use of having main() as static?

i was thinking that if we don't ever createobjects
of the class containing main(), then it makes no
difference having it as static or not...Yes it does.do u mean it does in the sense that in oder for the
program to run, we would have to instantiate that
class but for a static main()?It has already been answered in the thread. The method must be static since we don't want to create an instance in order to be able to execute the main method.
Kaj

Similar Messages

  • Dynamic Class Instantiation with getDefinitionByName

    Ok so I am trying to follow the following example in
    instantiating a class dynamically:
    http://nondocs.blogspot.com/2007/04/flexhowtoinstantiate-class-from-class.html
    My AS3 code looks like this:
    var myClassName:String = event.templateName;
    //Alert.show(getDefinitionByName(myClassName).toString());
    try {
    var ClassReference:Class = getDefinitionByName(myClassName)
    as Class;
    var myInstanceObject:* = new ClassReference();
    } catch( e:Error ) {
    Alert.show("Could not instantiate the class " + myClassName
    + ". Please ensure that the class name is a valid name and that the
    Actionscript 3 class or MXML file exists within the project
    parameters.");
    return;
    However I get an error: ReferenceError: Error #1065: Variable
    OrderEdit is not defined.
    The problem is that my class is located in an altogether
    different project directory from the the calling main project (I
    include this project with these classes I am trying to dynamically
    instantiate in the project source path).
    Every example I have seen so far involves some sort of hard
    coding. I am builidng a plugin/component that I intend to use in
    various places in my site and have any general hard code is
    UNACCEPTABLE. How can I make this process COMPLETELY HARD CODE
    FREE??
    Thanks a ton!

    I am also facing the same problem, I have imported swc (flash
    created) to flex library path (Flex project >> properties
    >> Flex build path >> Library path >> add swc)
    These swc files are icons for my applications with some
    scripts (written in flash, I am using UIMovieClip). So I want to
    make it dynamic.
    I write a xml with these component name and want to create a
    object and then add that object to my canvas according to xml data.
    if I code like this:
    var myIcon:IconA = new IconA()
    canvas.addChild(myIcon); //canvas is instance of Canvas
    then its working, but if I code like
    var myDynClass:Class = getDefinitionByName("IconA") as Class
    var myIcon:* = new myDynClass()
    canvas.addChild(myIcon); //canvas is instance of Canvas
    Then its showing me same error
    Error
    Error #1065: Variable IconA is not defined.
    So, I have seen your reply but didn't get it, how can I fix
    this problem using modules. or any other way...
    Thanks,

  • Class Instantiation Issues...

    Hi,
    We are currently having issuses with a Class Interface.  Everything was working fine with it, and now it says that the class is 'not instantiated'.  If you are in SE80 or SE24 and try to test a class (e.g. CL_HRRCF_APPLICATION_CTRL), you will get a pop-up that allows you to replace generic parameter types.  Now with the non-working class, it gives a screen similar to your transport organizer, with the class name at the top with '<not instantiated>' beside it, and a list of methods below it.  This Class is being used through the web.  Also, in the title bar in 6.40, it says, 'Test Class CL_HRRCF_GLOBAL_CONTEXT: No Instance'.
    <phew>... so, has anyone else run into a problem like this, and if not, does this make enough sense?  Is there a way of instantiating a Class Interface without calling it from a program, like generation?
    Best regards,
    Kevin
    Message was edited by: Kevin Schmidt

    Hi Kevin
    I am also working on an eRecruitment 3.0 ramp-up project. What I have found is that most of the classes etc used rely on other classes etc further up the chain, they cannot be tested in isolation. Instead it is normally necessary to set a breakpoint and then log into the eRecruitment Fornt end via a web browser. The class will then be instantiated in the normal process, as you work through the system pages, and called appropriately.
    This is a BSP issue. The class in question is a basic building block of the eRecruitment BSP pages.
    Regards
    Jon Bowes [ Contract Developer ]

  • Abstract class instantiation.?

    I have an Abstract class which is extended
    My question is:
    How can the Abstract class be instantiated:
    Animal[] ref = new Animal[3];
    In Java,we cannot instantiate Abstract class,so how does this
    work
    abstract class Animal  // class is abstract
      private String name;
      public String getName(){       
           return name;
      public abstract void speak();  
    class Dog extends Animal{
          private String dogName;
          public Dog(String nm){
         this.dogName=nm;
          public void speak(){       // Implement the abstract method.
          System.out.println("Woof");
          public String getName(){   // Override default functionality.
              return dogName;
    class Cow extends Animal{
          private String cowName;
          public Cow(String nm){
          this.cowName = nm;
          public void speak(){       // Implement the abstract method.
          System.out.println("Moo");
          public String getName(){
              return cowName;
    public class AnimalArray{
      public static void main(String[] args) {
      Animal[] ref = new Animal[3]; // assign space for array
      Dog aDog = new Dog("Rover");  // makes specific objects
      Cow aCow = new Cow("Bossy"); 
      // now put them in an array
      ref[0] = aDog;
      ref[1] = aCow;
      // now dynamic method binding
      for (int x=0;x<2;++x){
           ref[x].speak();
           System.out.println(ref[x].getName());
    }

    You mean to say that now we have a handle or a reference to the
    abstract class. Right ?
    But in the
    public static Test instance () {
            return new Test () {
                public void test () {}
        }How can you say 'return new Test()' as Test is an abtract class
    and what will public void test() return as this has no body ?

  • Understanding class instantiation

    Given classes A, B, and C where B extends A and C extends B and where all classes implement the instance method void doIt(). A reference variable is instantiated as �A x = new B();� and then x.doIt() is executed. What version of the doIt() method is actually executed and why?
    This says to me, I have just created an instance of B of class type A.
    I think class B's doIt() method is the one executed because of that.
    Does anyone have any insight into this?

    A static method can be replaced, which can look like overriding if you don't know the difference.
    For comparison
    public class A {
        public static void main(String[] args) {
            new B().doit(); // prints B.doit() !
            A x = new B();
            x.doit(); // prints A.doit() !
        public static void doit() {
            System.out.println("A.doit()");
    class B extends A {
        public static void doit() {
            System.out.println("B.doit()");

  • Inner class instantiation

    Compiling the following code gives me error
    public class A
      public A()
      boolean a=true;
      class B
      { // removed syntax error "Inner"
        B()
          a = false;
      public static void main(String [] arg)
        A a = new A();
        A.B ab = a.new A.B();
        System.out.println(a);
    }The error I get is
    "A.java": Error #: 200 : '(' expected at line 30, column 21
    could somebody advise me as what I am doing wrong??

    this will compile
    public class A
    public A()
    boolean a=true;
    static class B
    { // removed syntax error "Inner"
    boolean a;
    B()
    a = false;
    public static void main(String [] arg)
    A a = new A();
    B ab = new A.B();
    System.out.println(a);
    I was talking about a member inner class. Thanx anyway. Yahya's solution worked. Interesting thing is that the way I was instantiating it is mentioned in Java Sun Certified Programmer Book in Inner classes chapter. by Syngress. But that definitely seems to be a mistake.

  • Class instantiation only if allowed (ClassLoader?)

    I am implementing some runtime security checks for a project whereby I validate classes before they are allowed to be instantiated.
    Right now I use properties files and reflection to instantiate the classes, so a simple String comparison can tell me whether the class name is "allowed" to be instantiated. This can be checked just before calling Class.forName().
    Obviously, this does not keep someone from writing their own program that would instantiate my classes.
    I am trying to keep from having to go back and add a bunch of code in the constructor(s) of each class. I was thinking of subclassing ClassLoader, but have heard horror stories about them.
    Does anyone have any other ideas of how to handle this? Or perhaps some insight into ClassLoaders and whether they are easier to sub-class these days.
    thanks
    kleink

    ClassLoaders are easy to sub-class.
    The main problems people who post here seem to have with them are centered around a lack of understanding of loading classes in general.
    But I think that given your description of what you want to do, that creating a custom ClassLoader would be a good approach. Try subclassing URLClassLoader and you should not have to override too many methods (maybe just findClass()).

  • Calling EJB facades via class instantiated via reflection?

    We are loading plugins via Java reflection. Anything instantiated via newInstance() does not appear to have access to the Local interface.
    Right now, to get to the session bean we must use the Remote interface. This is annoying due to the performance, and seems completely unnecessary when everything is operating in one JVM.
    Tests were done to print out the JNDI namespace and the local interfaces don't seem to be accessible. Any advice?

    My project consists of an EJB package and WAR. I have not had any problem calling the local facades from JSP, Servlet, or web service in the EJB package.
    Further, I can use XStream reflection and do local EJB calls.
    It baffles me why I can't do the local calls in some classes via InitialContext lookups.
    I will post test code next week.

  • Class instantiation - and is this a pattern?

    Firstly, my apologies if my goal here is unclear. I am still learning the concepts and may perhaps have a lack of words for the appropriate terms or processes. Hopefully I can convey my meaning enough to get some feedback.
    I have a group of classes, all inheriting from a base class. My task is to add the functionality in these classes to another set of derived classes by simply creating instances of them in these classes constructor methods. To my knowledge this means the instance must take the class it's written in or (this) as it's parameter. My question is then really how should my external helper classes be written so they can be instanced in this way and is there a pattern that this idea conforms to and if so could someone explain this to me. My thanks in advance for any help, tips or directions to a good reference on this topic.

    It sounds a bit like the Strategy pattern.
    Your "helper" classes are providing various ways of performing a task on behalf of another class.
    AWT LayoutManagers implement strategies for laying out the Components in a Container. Have a look through that to see how it's done there.
    Whether your strategy classes need to take the "container" class in their constructor will depend on the functionality they provide. If their behaviour does not need to be cached then they could take a reference to the wrapper in each method call like LayoutManagers do.
    Hope this helps.

  • Dynamic Class Instantiating

    Hi,
    I need to dynamicaly instantiate classes at runtime, that is multiple instances, with different reference variables.
    I can easily intantiate a number of classes with different object variables, but i need to do it dynamically at runtime. anyone?

    I think u can better solve this by using Hashtable like data-structure.
    The key will be a String(external data like phone no.-as u said).
    The value will be the actual object which u r trying to load dynamically.
    u can load the class dynamically as follows.
    Class className=Class.forName("ClassName");
    Here class name is the name of the class whose instance u want to create dynamically.If u dont know the
    name exactly u need to use reflection.
    Object activeObject=className.newInstance();
    try this.
    -seenu_ch

  • Class instantiation through mxml - setting properties

    Hi,
    I'm trying to create a reusable component with an actionscript class.
    I'd like to be able to set a handful of the class' properties withmxml attributes. So far, I've had no success doing so.
    I've subset my problem into a separate, simplied project in an attempt to rule out any of the other parts of the real application interfering with what I'm attempting to accomplish. Unfortunately, my simplified project produces the same result.
    In my example, I'm just trying to set value of the property "myValue."  Can anyone tell me what I'm doing wrong? What am I missing?
    Thanks in advance for any help!
    Main application (TestProj.mxml)
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                      xmlns:s="library://ns.adobe.com/flex/spark"
                      xmlns:mx="library://ns.adobe.com/flex/mx"
                      minWidth="955" minHeight="600"
                      xmlns:pkg="pkg.*">
         <fx:Declarations>
              <!-- Place non-visual elements (e.g., services, value objects) here -->
         </fx:Declarations>
         <pkg:TestClass myvalue="some value" />
    </s:Application>
    Actionscript class (pkg\TestClass.as)
    package pkg
         import mx.controls.Alert;
         import mx.core.UIComponent;
         public class TestClass extends UIComponent
              private var _myvalue:String;
              public function TestClass()
                   Alert.show("myvalue=" + this._myvalue);     
              public function get myvalue():String
                   return _myvalue;
              public function set myvalue(value:String):void
                   _myvalue = value;

    Hi,
    The property gets set correctly, but the constructor of your class will always execute before the attributes - this is because Flex needs to create the instance and execute the c-tor before it can set the values on the instance.  Instead try something like this:
    <pkg:TestClass id="foo" myvalue="some value" initialize="{Alert.show(foot.myvalue)}" />
    This will execute the Alert.show when the component is being initialized.  If you need to put some init code in the component itself and that code relies on values set in MXML, then you can override UIComponent's public function initialize():void.
    -Evtim

  • Dynamic class instantiation

    Win2000
    SunOne Studio J2SE
    I am developing an application. I would like to instantiate classes and invoke methods dynamically, given a string containing the name of the class and/or a string containing the name of the method.
    I have the following code, and it compiles without error. However, when I run it, it throws a "ClassNotFoundException". I have read several articles that explain it as I have coded below.
    Any insights are appreciated. Thanks.
    try
    String className = "TestClass" ;
    String methodName = "OutMsg" ;
    Class testClass ;
    Object testObj ;
    Method testMethod ;
    testClass = Class.forName(className) ;
    testObj = testClass.newInstance() ;
    testMethod = testClass.getMethod(methodName, null) ;
    testMethod.invoke(testObj, null) ;
    catch (InstantiationException exc)
    System.out.println(exc) ;
    catch (ClassNotFoundException exc)
    System.out.println(exc) ;
    catch (IllegalAccessException exc)
    System.out.println(exc) ;
    catch (NoSuchMethodException exc)
    System.out.println(exc) ;
    catch (InvocationTargetException exc)
    System.out.println(exc) ;
    public class TestClass
    public void OutMsg()
    System.out.println("This is a test") ;

    You need to put complete class.
    I tried
    Class.forName("String");
    it complains that String is not found.
    But if I try
    Class.forName("java.lang.String");
    it works.
    MSN

  • Singleton class instantiated several times

    Hi all,
    I am trying to implement an inter-applet communication using a singleton class for registering the applets. The applets are in different frames on my browser; they are placed in the same directory and they use the same java console, so I am pretty sure they are running on the same JVM...
    However, when I register my applets, every applet creates its "own" registry class. I have put a message in the constructor of the register class to check what's happening:
    public class AppletRegistry extends Applet 
        //static hashtable maintaining the applet map
        private static Hashtable appletMap;
        private static int ct=0;
        protected static AppletRegistry registry;
        protected AppletRegistry()
            appletMap = new Hashtable();
    //  Returns the long instance of the registry. If there isn't a registry
    //  yet, it creates one.
          public synchronized static AppletRegistry instance()
               if (registry == null) {
                         System.out.println("new register");
                    registry = new AppletRegistry();
               return registry;
        //registers the given applet
        public void register(String name, Applet applet)
            appletMap.put(name, applet);
            ct++;
            System.out.println("Register: "+name+" "+Integer.toString(ct));
    }The output "new register" appears for every applet I register... What am I doing wrong?
    Thea

    I must admit that I never heard of classloader until
    now :-( (learning java for two or three months). Do
    you know a good tutorial about using classloaders? I
    have no idea where to start checking which
    classloaders are used.
    Thanks!
    TheaHi,
    I don't think there are much you can do about it. Two different applets can't share an instance.
    /Kaj

  • Urgent: Mysterious behavior in class instantiation

    Hi
    I have a Class A trying to instantiate a Class B , both of them being in the same jar. When a class C ( located in another jar) calls this method on Class A that instantiates B, execution seems to stop at that point. However there are no errors visible.
    When i create an Instance of class A and call the same method that instantiates B in a Junit test, it works fine.
    I am using jboss and have put the jars in the default/lib folder.
    Any insights into this would be highly appreciated.
    Thanks
    -DD

    The key words are "seems" and "visible." If execution really does stop there, then it's almost certainly because there was a Throwable. If this is the case, then the problem is the visibility of the error. The other likely possibility is that execution does not actually stop there, and you are misunderstanding what's happening. In ether case, you need more output statements around the area of the problem to find out what's going on.

  • Anonymous class instantiation expression with interface implementation??

    Is it possible to create an inline anonymous class instatiation expression that can implements an interface?
    For example:
    Frame myFrame = new Frame() implements WindowListner {
         public void WindowOpened(WindowEvent  e) {}
             +other interface methods....+
    }Apparently compiler doesn't like this code:(
    I know that I can create an extra named class with the interface, then instantiate it instead. But this is not what I want.
    (By the way, if someone wants to know why I want to do this, I say I think this may make my code simpler or look better, that's all:) )

    abstract class ListenerFrame extends Frame implements WindowListener {} This look pretty neat:)
    I guess I can rewrite my code then:
    abstract class FrameWithListener extends Frame
             implements WindowListener{}      //local class
    Frame myFrame = new FrameWithListener {
            public void WindowOpened {}
               blah, blah...
    }Not sure I can use abstarct class as local class, but otherwise I'll use it as a class member or some sort..
    Thank you for the reply
    Edited by: JavaToTavaL on Nov 27, 2009 4:04 AM
    Edited by: JavaToTavaL on Nov 27, 2009 4:04 AM

Maybe you are looking for

  • Issue on Changing the Payroll Area in Mid of the Month from Biweekly to Mon

    Dear Experts, I have an issue on payroll area which is changing from biweekly to monthly in Mid of the Month. One employee was retired on 29th of March, so his payroll area was changed from biweekly to monthly on 29th. For retire we are running the p

  • MacBook pro not starting. LOTS of issues trying to login. Looking for any kind of advice, I'm at a loss..

    Basically my Macbook pro isn't starting up correctly. Every time I start it up, I get a loading bar. Once the bar is finished, the computer just shuts off. Sometimes when it loads without the bar - It instantly takes me to OSX Utilities instead of th

  • Chat with an agent doesn't work

    I have been trying for the last hour to get into the chat with an agent feature, does this feature work? Has anyone else used it?

  • SOAP RECEIVER - no soap envelope sent

    Hi I am new to soap. When sending the SOAP request via the SOAP RECEIVER commchannel - the partner only reveives a plain xml with no SOAP-ENV. My comm channel settings are as follow: URL is set to the url of the receiver No other settings is marked.

  • Creating a dynamic Array

    Thanks for reply. I want to create a dynamic array and for this I used ArrayList Collection and Vector Class. I am using JDK 1.4.1 . But , I have a problem in that. In ArrayList, I used the following code: ArrayList al = new ArrayList(); while(rs.nex