Instantiating a class within itself ?!

Hi guys,I just started playing around with Java, trying to understand the core base of this language.
I have created a simple class and just-for-try I instantiated this class from inside itself.
public class PrivAndPublic{
PrivAndPublic o = new PrivAndPublic();
}//end of class
It doesn't give me any compiling error!
Doesn't it sound strange?!
I cannot understand how is it possible and it really seems a bug to me.
Thanks for any help!

What Darcia wrote make me suppose that a class is totally created with the first line of a java file (i.e. public class PrivAndPublic{ )and initialized by the constructor (which, if omitted, comes by default with no arguments)...after all this, the class can be instantiated many times I want from inside the class itself.
(I was thinking the class needed to reach the matching close curly brace to be possible to instantiate it)
But as phyzome said I have to be careful to do not make the object call the method which I put the object in, otherwise I will cause an infinite loop...as I did try ;)
Thanx guys, see you.

Similar Messages

  • Instantiating a class within a class

    I've got a package with 2 classes. The first, we'll call it
    C1, is being instantiated within the main body of code. In turn, it
    instantiates another class, C2.
    Problem is, the C2 instantiation is not happening. However,
    if I instantiate the class within the main code body, the
    instantiations within C1 work ok. A chopped down version of my
    code:
    // main.swf
    import stuff.*;
    var myC1:C1 = new C1();
    var myC2:C2 = new C2(); // remove this line and the line
    below stops functioning
    // C1.as
    class stuff.C1 {
    public function C1() {
    trace('C1 instantiated');
    var anotherC2 = new C2(); // this line doesn't work unless
    the line above is included
    // C2.as
    class stuff.C2 {
    public function C2() {
    trace('C2 instantiated');
    So if I take the classes out of the package it works also, so
    I'm guessing it has something to do with the way I'm importing the
    files maybe? I dunno. Any thoughts?

    What Darcia wrote make me suppose that a class is totally created with the first line of a java file (i.e. public class PrivAndPublic{ )and initialized by the constructor (which, if omitted, comes by default with no arguments)...after all this, the class can be instantiated many times I want from inside the class itself.
    (I was thinking the class needed to reach the matching close curly brace to be possible to instantiate it)
    But as phyzome said I have to be careful to do not make the object call the method which I put the object in, otherwise I will cause an infinite loop...as I did try ;)
    Thanx guys, see you.

  • Java Inner classes within the Threading paradigm

    Hi all.
    Im familiar with static nested classes, method local classes, inner classes and anonymous classes.
    But what I am a little perplexed by, is when exactly to use inner classes or static nested classes? (forgetting anonymous classes and method local classes).
    I read this article (http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html) and the first point makes for a good argument, but why nest the class? Why not define it as an external class?
    Also you typically find nested classes within the Threading paradigm, but why?
    I typically would create a top level class (non nested) that would implement the Runnable interface, override run() and then
    use this class when constructing a new Thread.
    Any clarification would be greatly received.
    Thanks and Happy Friday.

    Boeing-737 wrote:
    I read this article (http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html) and the first point makes for a good argument, but why nest the class? Why not define it as an external class?
    I was going to provide some reasons, but when I read the article I found they were already there. Following the DRY principle I'm going to let the article speak for itself.
    Also you typically find nested classes within the Threading paradigm, but why?No, I don't. If that's where you typically find them then you haven't had a varied experience.
    I typically would create a top level class (non nested) that would implement the Runnable interface, override run() and then
    use this class when constructing a new Thread.So carry on doing that, if it works for you.

  • How to get the JNDI name of an EJB from within itself

    Hello,
    I'm trying to find a way to get the JNDI name of a session bean from
    within itself.
    In the application I'm working on we need to support multiple
    customers. In order to do that, each EJB has a normal home and remote
    interface, a base class bean implementation and different children
    bean implemetations for each customer (when the logic for the
    customers is different). JNDI is used to get the proper implementation
    based on the customer.
    I've got an EJB that provides some services that are the same for all
    customers, except for the fact that it contains one variable that
    should have a different value depending on the customer. I don't want
    to creat subclasses just for that. What I want is to be able to get
    the JNDI name and set the variable based on the it.
    Is there a way to get the JNDI name for the EJB from within itself?
    TIA
    MJ

    Hi Pradeep,
    Please try referring to this post which is discussed earliar and seems its also answered.
    http://forums.adobe.com/thread/504861
    Thanks,
    Bhasker Chari

  • Instantiating Java class while WAS is starting

    Is there a possibility to register Java classes within the SAP WAS which will be instantiated while the server starts up?

    Hi,
    to be honest, I have only a rough idea - may be you can emulate this behaviour  by  a web application, where in the deployment descriptor the load-on-startup flag is set ?
    Barbara

  • Creating Instances of class within its definition

    Hi,
    I am a newbie to Java and am doing a course on Java. In one my assignments it asks us to develop the following method for a Class called CraftStock:
    "Define a new helper method void increaseStockCapacity() that creates a
    new expanded array as follows. It should create a temporary instance of
    CraftStock by using its single-argument constructor ? the value of the argument n is determined by the current size of the original craft stock array plus the
    extraCapacity constant. All items in the original array must be copied from the
    original array to the temporary instance of CraftStock. The array reference in the
    original array instance of CraftStock must then be reassigned to the new
    temporary array instance."
    My question is - is this possible - can one create an instance of a class from within its definition? I can't find anyhting on this from the books.
    Any help would be appreciated.
    Thanks
    Dev

    Isn't there a caveat to all this?
    If one creates an instance of a class within its own
    definition, doesn't one face the potential danger of
    attempting to access some part of the object which
    has not yet been constructed?nope. why would it? we're creating a new instance of the class, from scratch. we're not accessing any part of the object, we're creating a new one. the fact that this is being done within the definition of the class is irrelevant. by the time anything comes to call on a static method of the class, the class is initialized already. remember, static methods don't have any dependency on a particular instance
    sorry, that doesn't read very well, does it! what I mean is that the class itself is not the same thing as an instance of that class
    Message was edited by:
    georgemc

  • Calling classes within classes..

    This is what my code looks like:
    public class MainClass implements ActionListener
            methods not shown
        public void actionPerformed(ActionEvent event)
            if(event.getSource().equals(newKeyItem))
                  NewKeyGUI nkGUI = new NewKeyGUI();
             else if(event.getSource().equals(loadKeyItem))
                  LoadKeyGUI lkGUI = new LoadKeyGUI();
        class NewKeyGUI implements ActionListener
            /* methods not shown */
        class LoadKeyGUI implements ActionListener
            /* methods not shown */
    }When it performs the action for the newKeyItem in the MainClass nothing happens, but my GUI is set up perfectly.. When I compiled I got no errors due to the classes within the MainClass..
    So I am guessing that I am calling the 'sub-classes' incorrectly then.
    Please help me! thanks in advance!

    Your actionPerformed method does essentially nothing. The blocks of the if statements instantiate new objects, assign them to local variables, which then disappear when the block immediately ends. Unless the NewKeyGUI and LoadKeyGUI constructors do something as a side effect (which, IMHO, is bad design), nothing is happening hear other than instantiating objects unnecessarily.
    You probably meant to assign the new objects to existing fields -- so, get rid of the first "NewKeyGUI" and "LoadKeyGUI" on each line.
    Personally, I think it's also a red flag when you do event.getSource(). With anonymous inner classes, it's a lot easier now to create mini anonymous classes for each specific GUI widget as needed.

  • Trying to create object of a class within servlet - help!!

    I have created and compiled the following classes within
    C:\bea\wlserver6.1\config\mydomain\applications\DefaultWebApp\WEB-INF\classes
    1)LoginServlet
    2)LoginManager
    3)I have LoginServlet trying to create an object of type LoginManager, very simple,
    but I get the following errors:
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    4)I have the .java and .class files located within the same directory, so I don't
    see what's wrong here??? HELP!
    LoginManager looks like:
    public class LoginManager {
    public boolean authenticateUser(String username, String password){
              boolean status = false;
    //simple code for string matching
              return status;
    LoginServlet looks like:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class LoginServlet extends HttpServlet {
         // Constructors
         // Variables
         public static final String CONTENT_TYPE = "text/html";
         public boolean LOGIN_STATUS;
         // Methods
         public void service (HttpServletRequest req, HttpServletResponse res)
              throws IOException {
              String username = "";
              String password = "";
              LoginManager lm = new LoginManager();
              username = req.getParameter("username");
              password = req.getParameter("password");
              LOGIN_STATUS = lm.authenticateUser(username, password);
              res.setContentType(CONTENT_TYPE);
              PrintWriter out = res.getWriter();
              out.println("<html><head><title>Hello World</title></head>" +
                             "<body>Hello! Your login status is " + LOGIN_STATUS +
                             "</body>" +
                             "</html>");
         public void init (ServletConfig config) throws ServletException {
              super.init(config);

    Do you have . in the CLASSPATH when compiling your servlet?
    ron <[email protected]> wrote:
    I have created and compiled the following classes within
    C:\bea\wlserver6.1\config\mydomain\applications\DefaultWebApp\WEB-INF\classes
    1)LoginServlet
    2)LoginManager
    3)I have LoginServlet trying to create an object of type LoginManager, very simple,
    but I get the following errors:
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    4)I have the .java and .class files located within the same directory, so I don't
    see what's wrong here??? HELP!
    LoginManager looks like:
    public class LoginManager {
    public boolean authenticateUser(String username, String password){
              boolean status = false;
    //simple code for string matching
              return status;
    LoginServlet looks like:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class LoginServlet extends HttpServlet {
         // Constructors
         // Variables
         public static final String CONTENT_TYPE = "text/html";
         public boolean LOGIN_STATUS;
         // Methods
         public void service (HttpServletRequest req, HttpServletResponse res)
              throws IOException {
              String username = "";
              String password = "";
              LoginManager lm = new LoginManager();
              username = req.getParameter("username");
              password = req.getParameter("password");
              LOGIN_STATUS = lm.authenticateUser(username, password);
              res.setContentType(CONTENT_TYPE);
              PrintWriter out = res.getWriter();
              out.println("<html><head><title>Hello World</title></head>" +
                             "<body>Hello! Your login status is " + LOGIN_STATUS +
                             "</body>" +
                             "</html>");
         public void init (ServletConfig config) throws ServletException {
              super.init(config);
    Dimitri

  • How to import .jar files in order to use the classes within this file

    hello guys,
    I'm just wondering how can i import .jar files in order to uses the classes within this file.
    let's take an example:
    i have a folder in which I have many .jar files which contain classes to be called. the full path of this folder is set in the Classpath inside the enviroment variables.
    so does anyone have any idea how can i import these .jar files so i can use the classes?
    thank you.

    Hi,
    My problem is that: I created a Serializable class in a project. And I added this project (first project) to another project (second project). First project is appearing in the second project' s Libraries folder. No problem. I want to create a jar file from second project. i.e. I want to Build second project (I use NetBeans IDE). I am using Build Main Project tab under Run. It is falling out. I am finding it second project' s jar file under its folder. I am clicking on it. But it is NOT WORKING. Do you know WHY. Could you help me please?
    Thanks,

  • Reg: help on instantiation of class in workflow task

    Hi Geeks,
               I am trying to use class for Purchase order though standard workflow is available with BO. As per the requirement the triggering event is same as in the standard workflow with BO. Once the workfow is triggered ,The data is pulled to class from BO and custom release step is defined for release in class .
                  I face problem with the instantiation of class in workflow task while passed the po value and defined binding for the same after  reading  the document posted by jocelyn dart regarding this as follows :[www. wiki.sdn.sap.com/.../UsingABAPOOmethodsinWorkflowTasks |www. wiki.sdn.sap.com/.../UsingABAPOOmethodsinWorkflowTasks ]
    I am getting error as " Formal parameter " po number  " not defined.Please Advice.
    Regards,
    Kumar.

    Hi,
    I checked the same still no luck. I checked approx all combination.
    First I created a SOA-SAR file(jar file) , I extracted it and checked all jar files were there. orabpel.jar and bpm-services.jar and log4j jar. when i deployed that jar file. but it was not working
    then I put this in weblogic sever lib. it not worked.
    please tell me some points

  • Errors with CF 8.0.1 hotfix 3 and hotfix 4, "Object Instantiation Exception.Class not found"

    We need to get our servers up to date with the latest ColdFusion hotfixes in order to pass our security scans and policies. We have been following the Adobe instructions for installing the hotfixes, but we’re getting the same errors each time. The CF 8 hotfix 2 works fine, but once we install hotfix 3 and/or hotfix 4, we get the following errors:
    "Object Instantiation Exception.Class not found: coldfusion.security.ESAPIUtils The specific sequence of files included or processed is: C:\ColdFusion\wwwroot\WEB-INF\exception\java\lang\Exception.cfm, line: 12 "
    coldfusion.runtime.java.JavaObjectClassNotFoundException:
    We have dozens of servers running Windows XP, Netscape Enterprise Server 6.1 (I  know, don’t laugh), ColdFusion 8,0,1,195765, and Java Version 1.6.0_04. Just about  the only good thing about running XP on our servers is that it matches  our development boxes, so we have almost mirrored environments for dev,  test, and production. We do NOT have the CF install with the J2EE configuration.
    The crazy thing is, on tech note 51180 (http://kb2.adobe.com/cps/511/cpsid_51180.html), it says that the fix for bug # 71787 (Fix for "Object Instantiation Exception" thrown when calling a Java object constructor or method with a null argument under JDK 1.6.) was added in cumulative hotfix 2. However we don’t see this problem until we go to hotfix 3 (or 4).
    I’ve also been reading that other people had this same problem, and that the CF 8 hotfix 3 was not compatible with certain versions of JDK, then when you read the Adobe site for CF 8.0.1 hotfix 3, it says “Added the updated cumulative hotfix to make it compatible with jdk 1.4.x, 1.5.x and 1.6.x.”, so that makes me think that Adobe was supposed to have fixed this CF 8.0.1 hotfix 3 JDK incompatability issue - but unfortunately it's still not working for us. We have followed the instructions for removing the jar files and starting/restarting the CF server as directed, we’ve tried this 5-6 times, and still no luck.
    Recommendations? Seems like this is a ColdFusion bug to me – one that says is fixed on the Adobe site, but is not fixed in our environment. Please advise, thanks.

    For what it's worth, we had an MXUnit user describe a similar, though not identical, problem after installing the latest hotfixes. In his case, he's getting "NoSuchMethodExceptions".

  • Abstract class reference itself

    How do I reference an abstract class to itself.
    public abstract class SomeClass {
       public static SomeType SomeMethod(){
             SomeClass mine = new SomeClass();
       }It gives me an error saying it can not instantiate the class.

    Possible source of confusion: you can declare a variable of type abstract class and assign it an object of a derived class that fully implements the abstract class. For instance:
    abstract class SomeClass
         public static void SomeMethod(){}
         public abstract void greeting();
    class AnotherClass extends SomeClass
         public void greeting()
              System.out.println("hello");
    public class DemoAbstractClasses
         public static void main(String args[])
              SomeClass A = new AnotherClass(); // A's type is an abstract class
              A.greeting();  //polymorphism
    }

  • Smart Folder searches within itself

    After upgrading to SL last fall the Smart Folders started to misbehave in the following manner:
    The smart folder set to search "This Mac" would after restart search within itself. E.g I have created a Smart Folder finding all Word documents edited within the last week, called "Word last week". But the folder start to search within itself, e.g."Word last week" instead of in "This Mac". I have checked and, after some days, the query delivers different results if I change back to search within "My Mac".
    What can I do to force Smart Folders to search the whole harddrive and quit being so self-centered (self-referencing)?

    They aren't searching "within themselves" but searching wherever you told them to. If you click a saved search (AKA Smart Folder) and then select the Show Criteria option, you will see the name of the smart search next to the "This Mac"--but it is just the name, it is searching where you told it to when you created it. Evidently the programmers decided something had to occupy that spot in the search criteria, and opted to have it display the name of the Smart Folder.
    That said, there is a really bad bug in saved searches that involve date as a criteria. They aren't updating properly because the wrong thing is being added to raw query of the search when you create it. Thus if you want a Smart Folder that finds MS Word docs created in the last 3 days, it won't update. If you use it next week it will continue to search for the created date of files from when you made it. I suspect this bug is what is throwing your results off.
    Francine
    Francine
    Schwieder

  • Advice on instantiating a class

    Is it better to instantiate a class within an if statement several times in a page.
    if(this condition exists){
    methodsClass mc = new methodsClass();
    mc.useMethod();
    if(this condition exists){
    methodsClass mc = new methodsClass();
    mc.useAnotherMethod();
    }Or is it better to instantiate a class at the top of the page outside of an if statement:
    methodsClass mc = new methodsClass();
    if(this condition is true){
    mc.useMethod();
    if(this condition is true){
    mc.useAnotherMethod();
    }Or does it matter?
    I guess what I am trying to say is: is there a performance hit if I create several instances of the methodsClass?
    TIA!

    If you are going to use the class instance only once in the method (depending on the if's), then it probably doesn't matter, except to save a few lines of code. But if the 2 if statements are separate and both can be executed on the same request, then better to create 1 instance outside the if's cuz that way you're only creating 1 object.

  • ITunes is totally frozen with multiple paints of same screen within itself. Also incredibly slow. Are there alternative players I can use with my iPhone, or must I use iTunes with my iPhone? iTunes is effectively unusably slow.

    iTunes is totally frozen with multiple paints of same screen within itself. Also incredibly slow. Are there alternative players I can use with my iPhone, or must I use iTunes with my iPhone? iTunes is effectively unusably slow. I am using Windows 7.
    I only use it once every few weeks and each time it is more disappointing than the previous time. does it run better on a Mac than Windows? Is this app really the future of media? Really?

    I am using iTunes 11.1.3 -- The most recent version. When I select something from my albums it just freezes. I have restarted it a few times with same result.

Maybe you are looking for

  • Logic 9 Issue Triggering Wrong 3rd Party Samples

    I know the question says 3rd party but bear with me because I have ruled out issues with the 3rd party libraries and players. This is my Issue: So far no one from 8dio, Native Instruments, or Apple can fix this and I am completely out of ideas. I rec

  • Go back to previous location after linking to another page in the same document

    I have set up links in a pdf file and would like to have the form go to the page view attached to the link and then return to the location that initiated the link.  I usually use bookmarks to move around pdf forms, but the user didn't want to see the

  • Registration  of new product

    We alraedy have two products (Crystal Reports Server) registered.  We got a new Busiiness Objects XI 3.1 this week.  The Registration Wizard seems to be continually looping and I cannot get further than the logon screen. I accessed my SAP Support Por

  • Using Calibration Executive for PXI-5610 using PXI-5124

    Hi guys, We've been trying to calibrate PXI-5610 but the Calibration Executive software pop up an error of PXI-5122 requirement but we don't have the module, we have the PXI-5124 instead. We have tried to use the unsupport but it's not working too. W

  • Big problem with 8.0.100

    Hi. Three weeks ago we upgraded our three 5508 controllers from 7.5 to 8.0.100, and since then the controllers (random wich one) suddenly reboots 2-3 times a week. Before upgrade it has been rock solid. 1. Anyone knows when next version of 8.x will b