Instantiate an instance inside its class

I always read codes like following:
Class A {
A a = new A( );
Could anybody tell me why a class is able to instantiate its instance inside itself.
Another example:
Class A {
B b = new B( );
Class B{
A a = new A( )
When Class A is running, it calls Class B, but when Class B is instantiated
, it needs to call Class A. I am always puzzled about this kind of codes.

Everything in the world is an object - not only the building, but also the blueprint for this building is some kind of sheet of paper.
In Java, the Class Objects are loaded as soon as you go into runtime. The VM recognizes all necessary classes, and creates one single instance of them. So, static attributes are indeed a singleton pattern on class level...
A class even has an own constructor. This constructor looks like this:
class ClassA{
      // Insert Class Constructor input here
}All static attributes are implicitly constructed in this class constructor.
However, what you have written, is just a simple Form of:
class ClassA{
   ClassA a;
   public ClassA(){
     a = new ClassA();
}This is indeed a neverending loop, so this doesn't make sense. But it isn't unusual to hold a reference to another object of the same type.

Similar Messages

  • Reassign class variable to a blank instance of its class

    When I declare a class variable
    private var myVar:MyClass = new MyClass();
    It creates a new instance of that class that will trace as [Object MyClass].
    However, as soon as I assign it to something
    myVar = thisOtherVar;
    It will now trace as [Object thisOtherVar].
    I need to get it back to where it's just an "empty" blank class instance, if that makes any sense at all.
    How do I go about doing that? Thanks!

    I'm brand new to OOP - I've been watching iTunes U videos and reading books but it's still all pretty abstract in my mind and it's difficult for me to pin point how all that stuff translates to actually writing good code.
    Basically, it's an open ended kid's dictionary. You drag the lettes to drop boxes, touch the check to see if it's a word, and then a picture representing the word pops up on the screen.
    All of it works except if you try to remove a letter that's already been placed. Originally, I wanted the check button to do a sweep of the dropped letters and see if they had formed a word - but I couldn't figure out a way to do that. So then I started tracking movements of letters in real time, and that's when it got really confusing. I think I just need to start over and try to make the code a bit cleaner. Right now this is what I've got:
    if (currentUsedBlank is BlankSquare) {  //if they have removed a letter that has already been dropped
                    if (currentUsedBlank != currentBlank) { //and it's been placed back on a different square
                        currentUsedBlank.letter = null;
                else {
                    currentUsedBlank.letter = null;
                if (this.dropTarget.parent is BlankSquare && currentBlank.letter == null) {
                    SpellingGlobals.lettersInBlanks[SpellingGlobals.lettersInBlanks.length] = this;
                    this.x = this.dropTarget.parent.x + 10;
                    this.y = this.dropTarget.parent.y - 10;
                    var myClass:Class = getDefinitionByName(getQualifiedClassName(MovieClip(this))) as Class;
                    var newLetter:MovieClip = new myClass();
                    newLetter.x = currentLetter.startPoint.x;   
                    newLetter.y = currentLetter.startPoint.y;
                    newLetter.letter = currentLetter.letter;
                    newLetter.reference = currentLetter.reference;
                    newLetter.startPoint.x = currentLetter.startPoint.x;
                    newLetter.startPoint.y = currentLetter.startPoint.y;
                    newLetter.isVowel = currentLetter.isVowel;
                    currentBlank.letter = currentLetter.letter;
                    if (SpellingGlobals.isCaps == true) {
                        newLetter.txt.text.toUpperCase();
                        if (SpellingGlobals.isColor == true) {
                            if (newLetter.isVowel) {
                                newLetter.txt.textColor = SpellingGlobals.colorVowel;
                            else {
                                newLetter.txt.textColor = SpellingGlobals.colorCon;
                    MovieClip(root).addChild(newLetter);
                    SpellingGlobals.copiedLetters[SpellingGlobals.copiedLetters.length] = newLetter;
                    currentBlank.alpha = 0;
                else {
                    this.x = MovieClip(this).startPoint.x;
                    this.y = MovieClip(this).startPoint.y;
                this.stopDrag();

  • Referencing a instance inside a Class

    Hi --
    I am working on converting a movie clip to a Class so that I
    can more easily
    reuse it in later projects.
    I have pretty succesfully converted my AS code from my
    include file to a
    Class file. However, I have two objects on the stage, topBG
    and botBG and
    whenever I reference these items inside my code, such as
    botBG._y I get an
    error at compile time saying "There is no property with the
    name 'botBG'"
    How can I set it so these assets can be referred to inside my
    code?
    The code worked fine when it was just a movie.. Also, this is
    ActionScript
    2.0.
    Thanks
    Rich

    Hi --
    Thanks for responding. What I had created was this:
    I have a movie clip, "MainClip" with two movie clips ("ClipA"
    and "ClipB")
    inside that clip.
    I put MainClip on the stage (_root) and had Actionscript code
    in the main
    time line. I referenced ClipA & ClipB this way:
    MainClip.ClipA
    MainClip.ClipB
    Now, I want to turn MainClip into a class, "classMainClip".
    However, having
    moved the Actionscript into the class AS file and changed the
    above
    reference to just
    ClipA
    ClipB
    I get an error at compile time.
    How do I refer to the movie clips, "ClipA" and "ClipB" inside
    the
    actionscript that is the over lying class of which I want
    these clips to be
    a part?
    Hopefully I've explained this right.
    Thanks,
    Rich
    "kglad" <[email protected]> wrote in message
    news:gibuh8$qbh$[email protected]..
    > you want class instances to be able to reference each
    other?

  • Generic instance maker and class definition in separate files - problem

    file: genericinstantiator.java
    package testGenericInstantiator;
    public final class GenericInstantiator {
         public <T> T makeInstance(Class<T> c) {
              T instance = null;
              try {
                   instance = c.newInstance();
              } catch (IllegalAccessException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (InstantiationException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              return instance;
    file: genericinstantiatorusage.java
    package testGenericInstantiator.usage;
    import testGenericInstantiator.GenericInstantiator;
    final class SillyClass {
         public void sayBoo() {
              System.out.println("boo");
    public final class GenericInstantiatorUsage {
         public static void main(String[] args) {
              GenericInstantiator gi = new GenericInstantiator();
              SillyClass sc = gi.makeInstance(SillyClass.class);
              sc.sayBoo();
              System.exit(0);
    thrown exception:
    java.lang.IllegalAccessException
    on the line 'instance = c.newInstance();' in instantiator
    reason in jdk:
    if the class or its nullary constructor is not accessible.
    question:
    how to avoid this? (in my situation, the place of making instance and its class MUST be separated in another files)
    Edited by: gizmo640 on Mar 27, 2008 11:39 AM

    package testGenericInstantiator;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    public final class GenericInstantiator {
         public <T> T makeInstance(Class<T> c) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
              T instance = null;     
              Class[] emptyParams = {};
              Constructor<T> con = c.getDeclaredConstructor(emptyParams);
              con.setAccessible(true);
              instance = con.newInstance();
              return instance;
    }setting constructor to accessible works well too

  • Indexing instances of specific class inside MovieClip authored with Flash Pro

    Hi there.
    I'm writing a class that extends MovieClip and that is linked to the MovieClip Object authored via Flash Pro during development (Father object).
    The hierarchy of this MovieClip Object is hidden from me - everything I know is that it may contain instances of other Class that was authored during development and extends MovieClip in the same manner (Son objects).
    I have no information regarding names or hierarchical positions of these Son objects inside Father object.
    Now the question is: how to get them listed?
    So approach I've taken was to implement current events:
    public class Son extends MovieClip
         public static const INITIALIZED : String = "son_initialized";
         public function Son ()
              this.dispatchEvent (new Event (INITIALIZED));
    public class Father extends MovieClip
         public var son : Vector<Son>;
         public function Father ()
              son = new Vector<Son> ();
              this.addEventListener (Son.INITIALIZED, this.onSonInitialized);
         public function onSonInitialized (event : Event)
              this.son.push (event.target);
    Well, this code compiles with no errors whatsoever, but it turns out that onSonInitialized gets never called. I assume that's because children constructors are called ahead of their parent one.
    Is there any way to get them listed?
    Thanks in advance.

    kglad,
    I'm trying to get an array of references to Son objects (Son extends MovieClip), randomly located deep inside display list hierarchy of Father object (extends MovieClip too).
    The Father movieclip is authorized in Flash Professional and is a black box for me - I can only manipulate Father.as and Son.as.
    Since I can't know exactly their pathes and names (i.e. father.child1.child5OfChild1.son32 for example), I decided to make them self-aware, dispatching event during construction time, messaging everybody that this instance of Son exists:
    public function Son ()
         this.dispatchEvent (new Event (INITIALIZED));
    And then I attached a listener inside Father's constructor:
    public function Father ()
         this.addEventListener (Son.INITIALIZED, this.onSonInitialized);
    The idea was that this event listener should have been catching all the Sons, located inside Father. But it doesn't work that way - Father's constructor seems to be called after all constructors of its children, so this event listener catches nothing.
    I've worked this around by straightforward display list traversing - it works, but doesn't look so elegant. May be there is still a way to make it work through events?

  • How do i create a single instance of a class inside a servlet ?

    how do i create a single instance of a class inside a servlet ?
    public void doGet(HttpServletRequest request,HttpServletResponseresponse) throws ServletException, IOException {
    // call a class here. this class should create only single instance, //though we know servlet are multithreaded. if, at any time 10 user comes //and access this servlet still there would one and only one instance of //that class.
    How do i make my class ? class is supposed to write some info to text file.

    i have a class MyClass. this class creates a thread.
    i just want to run MyClass only once in my servlet. i am afriad, if there are 10 users access this servlet ,then 10 Myclass instance wouldbe created. i just want to avoid this. i want to make only one instance of this class.
    How do i do ?
    they have this code in the link you provided.
    public class SingletonObject
      private SingletonObject()
        // no code req'd
      public static SingletonObject getSingletonObject()
        if (ref == null)
            // it's ok, we can call this constructor
            ref = new SingletonObject();          
        return ref;
      public Object clone()
         throws CloneNotSupportedException
        throw new CloneNotSupportedException();
        // that'll teach 'em
      private static SingletonObject ref;
    }i see, they are using clone !, i dont need this. do i ? shouldi delete that method ?
    where do i put my thread's run method in this snippet ?

  • How to create the instance of a class and to use this object remotely

    I have to change a standalone program to do it working on a local net.
    the program is prepared for this adjustment, because the only problem for this change came from the use of the database; and, in the application, all the accesses to the database come from only a class that supplies a connection to the database.
    In this way I think that I could have (in a local net) a "server application" that has the database embedded inside it.
    Furthermore, some client applications (running in different computers of the net) could get access to the database through the connection that comes from an instance of the class that, in the "server application", is made to provide the connection to the database.
    I think this could be a good idea...
    But I don't have practice with distributed applications and I would ask some suggestion about the way to realize my modification.
    (in particular how to get and use, in the "client applications", the instance of the class that give the connection to the database from the "server application").
    I would have some help..
    thank in advance
    regards
    tonyMrsangelo.

    tonyMrsangelo wrote:
    I have to change a standalone program to do it working on a local net.
    the program is prepared for this adjustment, because the only problem for this change came from the use of the database; and, in the application, all the accesses to the database come from only a class that supplies a connection to the database.
    In this way I think that I could have (in a local net) a "server application" that has the database embedded inside it.
    Furthermore, some client applications (running in different computers of the net) could get access to the database through the connection that comes from an instance of the class that, in the "server application", is made to provide the connection to the database.
    I think this could be a good idea... Which is why JEE and implementations of that exist.
    But I don't have practice with distributed applications and I would ask some suggestion about the way to realize my modification.
    (in particular how to get and use, in the "client applications", the instance of the class that give the connection to the database from the "server application").
    You can't pass a connection from a server to a client. Nothing will do that.
    As suggested you can create a simple RMI server/client set up. Or use a more feature rich (and much more complex) JEE container.
    RMI is simple enough for its own tutorial
    [http://java.sun.com/docs/books/tutorial/rmi/index.html]
    JEE (previously called J2EE) is much more complex and requires books. You can get a brief overlook from the following
    [http://java.sun.com/javaee/]

  • I want to run single instance of my class ?

    i have a class with name Abc, i want when my Abc class is
    in running mode then i cant run my Abc class again untill my
    Abc class not exit.
    i want to do that in pure java, i have one logic but it is not
    proper salution.
    my logic is that when my programe is start first check a temprery file
    which is created by my programe and when i want to exit then i delete
    that temprery file.
    but if computer is shutdown unproperly and my programe is in running mode then my file is not delete.
    please any body give me help.
    i m thanksfull.
    Arif.

    Hi,
    let's make it more precise as so "if my class is in running mode" is not very precise - I guess, you are not talking of a class which has implemented the Runnable interface and is executed via "new Thread(Abc).start()". I think, you want a class, which can only have one instance of it at a time, right?
    It is no problem, to make a class, which has only one instance - it is called a Singleton class - it consists of the following:
    public class MySingleton extends Object // or any other class
    public static final instance = new MySingleton();
    //the trick here is to declare its constructor private
    private MySingleton() { super(); }
    // some other methods here
    }There is only one instance of this class accessible via MySingleton.instance. The problem with it is, that it doesn't match your requirements, as so you are not able to instantiate this class ever again, even so you would declare the "instance" field not final and set it to null.
    What you can do now is dealing with security managers - check the documentation of the newInstance() method of the Class class and the SecurityManager class, there you will find several links to documentation related with the use of an security manager.
    greetings Marsian
    P.S.: all these *** in the text are the letters a s s :(

  • [svn] 4222: Now that Shader is a first class Embed, we' ve modified the interface for ShaderFilter to accept a Shader instance directly (or Class representing a Shader Embed).

    Revision: 4222
    Author: [email protected]
    Date: 2008-12-03 10:37:15 -0800 (Wed, 03 Dec 2008)
    Log Message:
    Now that Shader is a first class Embed, we've modified the interface for ShaderFilter to accept a Shader instance directly (or Class representing a Shader Embed).
    Reviewer: Pete Farland
    QE Notes: Mustella tests require updating.
    Doc Notes: ASDocs have been update, just sanity check.
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/effects/effectClasses/FxAnimateFilterInst ance.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/filters/ShaderFilter.as

    So this may be a kludge, but eventually I got it. In this case the appDelegate is waking up NIB's and subsequently causes the 'viewDidLoad' method to be called in the Object that manages the NIB.
    The problem was how to get 2 objects that had each been woken by the appDelegate to be aware of each other and be able to use methods in the other.
    In the appDelegate
    @class AViewControllerObject;
    @class A2ndVCObject;
    @interface AppDelegate
    AViewControllerObject * aViewControllerObject
    A2ndVCObject * a2ndVCObject;
    @property (
    @property (
    @end
    @implementation AppDelegate
    @synthesize aViewControllerObject;
    @synthesize a2ndVCObject;
    //instantiate the NIB's and place in the 'controllers' array
    aViewControllerObject = [[AViewControllerObject alloc]
    initWithNibName:@"aViewControllerNIB" bundle: nil];
    [controllers addObject: aViewControllerObject];
    a2ndVCObject = [[A2ndVCObject alloc]
    initWithNibName:@"a2ndVCNIB" bundle: nil];
    [controllers addObject: a2ndVCObject];
    So to make the 1st ViewControl Object aware of the 2nd viewControl Object, make the following method call from the appDelegate:
    [aViewControllerObject assignA2ndVCPointer: (A2ndVCObject *) a2ndVCObject];
    ....and in aViewControllerObject:
    @class A2ndVCObject;
    @interface AViewControllerObject
    A2ndVCObject * a2ndVCObject;
    @property (
    @end
    @implementation AViewControllerObject
    @synthesize a2ndVCObject;
    - (void) assignA2ndVCPointer: (A2ndVCObject *) pointer{
    self.a2ndVCObject = pointer;
    So this may seem bogus to 'old hands' but its the only way I could figure it out.
    If anyone has a better way, I'd love to hear it!!
    -- thanks for listening

  • How to access var in outter class inside inner class

    I've problem with this, how to access var number1 and number2 at outter class inside inner class? what statement do i have to use to access it ? i tried with " int number1 = Kalkulator1.this.number1; " but there no value at class option var y when the program was running...
    import java.io.*;
    public class Kalkulator1{
    int number1,number2,x;
    /* The short way to create instance object for input console*/
    private static BufferedReader stdin =
    new BufferedReader( new InputStreamReader( System.in ) );
    public static void main(String[] args)throws IOException {
    System.out.println("---------------------------------------");
    System.out.println("Kalkulator Sayur by Cumi ");
    System.out.println("---------------------------------------");
    System.out.println("Tentukan jenis operasi bilangan [0-4] ");
    System.out.println(" 1. Penjumlahan ");
    System.out.println(" 2. Pengurangan ");
    System.out.println(" 3. Perkalian ");
    System.out.println(" 4. Pembagian ");
    System.out.println("---------------------------------------");
    System.out.print(" Masukan jenis operasi : ");
    String ops = stdin.readLine();
         int numberops = Integer.parseInt( ops );
    System.out.print("Masukan Bilangan ke-1 : ");
    String input1 = stdin.readLine();
    int number1 = Integer.parseInt( input1 );
    System.out.print("Masukan Bilangan ke-2 : ");
    String input2 = stdin.readLine();
    int number2 = Integer.parseInt( input2 );     
         Kalkulator1 op = new Kalkulator1();
    Kalkulator1.option b = op.new option();
         b.pilihan(numberops);
    System.out.println("Bilangan yang dimasukkan adalah = " + number1 +" dan "+ number2 );
    class option{
    int x,y;
         int number1 = Kalkulator1.this.number1;
         int number2 = Kalkulator1.this.number2;
    void pilihan(int x) {
    if (x == 1)
    {System.out.println("Operasi yang digunakan adalah Penjumlahan");
            int y = (number1+number2);
            System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 2) {System.out.println("Operasi yang digunakan adalah Pengurangan");
             int y = (number1-number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 3) {System.out.println("Operasi yang digunakan adalah Perkalian");
             int y = (number1*number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 4) {System.out.println("Operasi yang digunakan adalah Pembagian ");
             int y = (number1/number2);
             System.out.println("Hasil dari operasi adalah =" + y);}
    else {System.out.println( "Operasi yang digunakan adalah Pembagian ");
    }

    Delete the variables number1 and number2 from your inner class. Your inner class can access the variables in the outer class directly. Unless you need the inner and outer class variables to hold different values then you can give them different names.
    In future place code tags around your code to make it retain formatting. Highlight code and click code button.

  • Centering an image inside its container

    Hi,
    I have been placing several images with text on a web page on which I have been using CSS3 to float the images either left or right so that my text wraps around the image.
    Now, at the bottom of this same page, I want to add a wider image that I do not want to wrap text around.  I just want the image to centered on my page (or in its container I guess I should say, which is a div).
    If anyone could tell me the best way to do this, I would greatly appreciate it.
    Thanks in advance,
    Paul

    Thank you Ken,
    I created the .clearing rule as you suggested and added the <hr class="clearing" /> after the end of the paragraph that wraps around my second (and final) floated image.
    After the <hr class="clearing" />, I have my image reference for the image I want to be centered inside its containing DIV as follows....
    <hr class="clearing" />
    <p><img src="Images/pk_38_41_43.jpg" alt="Membrane Casting Line" width="612" height="367" class="center"/></p>
    ...the class="center" is a class I created where I set the left and right margins to "auto", hoping that this would do the job.  This didn't work.  My image appears all the way to the left.  If you can give me a hint what I should do to get it centered, I'd really appreciate it.
    Thanks again for your help,
    Paul

  • OnEnterFrame inside a class

    I don't have a problem as much as just a lack of
    understanding:
    Question: Will I run into any problems using onEnterFrame
    inside a class? I know that onEnterFrame events can overwrite each
    other if they are written dynamically, but I'm not sure how this
    effects classes...
    Also, onEnterFrame is an event of the movie clip class right?
    ...does that even matter...? What happens if I declare an
    onEnterFrame event inside a method inside my class: will it even
    work? will it effect the movie clip from which the class.method is
    being called?
    Sigh... Hopefully you get the idea of what I'm having trouble
    grasping. Please explain any concepts you think I appear to be
    missing. I'm new to classes - thanks for your help.

    >>Question: Will I run into any problems using
    onEnterFrame inside a class?
    No.
    >>Also, onEnterFrame is an event of the movie clip
    class right? ...does that even matter...?
    No. Here is a brief explanation how it works.
    First of all, a class is a custom object. Don't think of a
    class as a bunch of code, it's a custom object with its own
    properties and methods. So when you say: "What happens if I declare
    an onEnterFrame event inside a method inside my class: will it even
    work?" you are thinking: "there is no timeline". Yes, there is.
    When you declare:
    private var my_mc:MovieClip;
    you are saving the functionality of the MovieClip Class in
    my_mc. Therefore, my_mc will have a timeline and all other
    properties and methods of the MovieClip Class. (By comparison:
    usually you don't need all the functionality of the MovieClip
    Class, so AS3 offers us the Sprite Class which is a basic
    implementation of a movieclip and that saves overhead).
    In a method you can use:
    private function mover(target:MovieClip):Void{
    target.onEnterFrame=function():Void{
    this._x+=2;
    passing the my_mc to function mover as a parameter. If at
    some time you want to stop the onEnterFrame you delete it just as
    you would using it in code on the timeline.
    Again. The most important thing to understand is that a class
    is not a bunch of code, it's a (custom) object with its own
    properties and methods.

  • How to call a function inside a class? 

    Hello, i am trying to fire a function onPress .. this
    function is inside a class.
    In this function i refer to another function inside the calss
    to call a Tween. It never arrives in the second function.
    I tried to make an example.
    In the fla file i have:
    var test:makeMovie = new makeMovie(this);
    You will see a red squere and you can press on it. It should
    run the tween class. Am i using the delegate class wrong?

    I always have to use test movie and trace a couple of times
    each time I start to use Delegate.
    It wraps function.apply I think, which I tend to use more
    often.
    try using:
    Container.onPress = Delegate.create(this,setAlpha);
    and then just
    setTween()
    inside your setAlpha....
    That's conceptually how I think I would try it above if I was
    doing something similar.
    I'm not sure it would have the desired effect even if the
    delegate was executed as you have it coded. Unless you want
    setTween's execution scope to be the Container clip in which case
    you might need to do what kglad said and change the Container
    reference to 'this'.
    The way you have it at the moment inside setAlpha the
    Delegate.create is simply creating a function...and not excuting
    it.
    its like : function something(){trace('what')}
    and not like : something();
    Below is some quick code that helps show how things work.
    Notice that I assigned the delegate function to mainFunc....so that
    along with the last example might provide a clue. Just paste it on
    a frame and take a look at what's happening.

  • "this." inside as2 classes

    Can any one say, if i should use "this." inside my classes to
    refer class
    variables and methods? What is its advantage and
    disadvantage? Does this
    help compiler/flash player in any way.
    please provide some useful links which explain more.
    Cheers,
    Sajeev

    when it's appropriate you can use "this". so, if you've just
    created a movieclip and you're defining a mouse handler for it,
    it's appropriate to use this within the handler's scope.
    but to refer to a class member, i use a private variable in
    the constructor function to use throughout the class so i don't
    have scope issues outside the constructor function.

  • How to synchronize a method for all instances of a class

    Hi,
    How to make a method synchronized for all instances of a class? If a simple method is synchronized, then multiple threads cannot access it at the same time. If we make the method as static, then we are making it synchronized at class level.How to make a synchronized method so that no two instances (objects) of a class can access it at the same?
    Thanks
    Neha

    Neha_Khands wrote:
    There is nothing wrong with that. Actually this question was asked in an interview. They didnt want to create a static method. They told me that synchronization can be achieved at instance level also. and for that we have to call some Class.getInstance().synchronied method inside constructor. Kind of a dumb question. First, synchronization does not occur "at a class level" or "at an instance level." Syncing is always the same--a single object's lock is obtained, which prevents any other threads from obtaining that lock. The only thing that makes it appear that there are special cases is that declaring a method synchronized obtains the lock associated with the instance or with the Class object for that class. But that's just syntactic sugar. The Class object lock is identical to the instance lock, which in turn is identical to a lock on some other arbitrary Object created just to serve as a lock. There's no such things as "locking the class" or "locking the instance."
    Second, and more important, making an instance method synced across all instances is a grotesquely artificial situation, IMHO, and if it were to ever come up, the right way to do it is to have that instance method call a static synchronized method.

Maybe you are looking for