Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple way to call other classes Methods. How? 1

Status
Not open for further replies.

razovy

Programmer
Feb 10, 2004
4
US
I have, for example, two classes:
public class Math {} {
public int Power3( int x){
return (x*x*x);
}
}
// and in the same module:
public class A(){
private int y;

public int Get_Pow3 (int mmm){
y = Power3(mmm);
}
}


And it causes Error.

This:

public int Get_Pow3 (int n){
Math MATHHH;
y = MATHHH.Power3(n);
}

works, but looks awfull

Question: How can I solve this issue?


I don't want any inheritance, any separated module, etc.

 
In order to access a public method exposed by another class, you must either:
1) Create an instance of that class in the area where you want to call it from (what you did to get it to work).

2) Make the method static, which means that you no longer need an instance, but are able to access the method by prefixing it with the class name.

An example of #1:
Code:
public class Math {} {
   public int Power3( int x){
      return (x*x*x);
   }
}

public class A(){
   private int y;
   
   public int Get_Pow3 (int mmm){
     Math MyMath = new Math();
     y = MyMath.Power3(mmm);
   }
}
There are numerous variations on this -- the MyMath variable could have had class scope instead of being declared in the method, it could have been passed in, it could have been inherited from a parent class, etc. But it all comes down to the idea that you need to create an instance of the Math class before making use of it.

An example of #2:
Code:
public class Math {} {
   public static int Power3( int x){
      return (x*x*x);
   }
}

public class A(){
   private int y;
   
   public int Get_Pow3 (int mmm){
     y = Math.Power3(mmm);
   }
}
What happens here is that the Power3 method is shared amongst all instances of the Math class. You can call it from an instanced method within Math, but you cannot go the other way (a static method calling an instanced method) without an instance to operate on.

Using a static method is most useful when you have some small utility function that does not depend on it's class maintaining any state information. You'll see them used that way in the .NET framework, such as in the XmlConvert class.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top