Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
can any1 tell me how we can call the method of the class without creating object but the by reference
Posted

make these methods static.
see
Example
 
Share this answer
 
and as a 3. solution;

you can address the object in a anonymous class:

Java
public Foo(){

public void bar(){
  Object oObject = new Object();
  Object.addListener(new IListener{
      
       public void ObjectChanged(Event oEvent){
           Foo.this.funnyAction();
       }
    }
  }
}

}


It always depends on the context of calling an Object. Butt in general you should use as less public static as possible.
 
Share this answer
 
If you have a reference to an instance of the class (that someone else created for you) then just call the method. If, on the other hand, you haven't it then you have to make the method static (if possible).
 
Share this answer
 
Just in case you want to know how it works.
When a class is loaded and before any instances are created, the static variables are assigned, the static constructor is called and any static methods are made available. There is no need to create any instances:

Java
class PlumPudding {
    // the first thing is the static variables:
    public static final boolean ADD_BRANDY = true;
    private static List<coin> coins;

    static {
        // second thing to happen is to run the static constructor:
        PlumPudding.coins = new ArrayList<coin>();
        PlumPudding.coins.add(new Coin(1));
        PlumPudding.coins.add(new Coin(2));
        PlumPudding.coins.add(new Coin(5));
        PlumPudding.coins.add(new Coin(10));
        PlumPudding.coins.add(new Coin(20));
        PlumPudding.coins.add(new Coin(50));
    }

    public static Coin getRandonCoin() {
       // now this can be called without creating an object
    }
}</coin></coin>
 
Share this answer
 
v2
Dude,


First of all u should know the basics of OOPs.

What does object creation really means?

Go throw the folowing link before u proceed.
http://cscie160-distance.com/nonstatic.html[^]
 
Share this answer
 
Comments
Nagy Vilmos 19-Dec-11 6:36am    
1 voted as this adds nothing to an already answered question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900