0

I would like to implement a method that I use in another class in my project package.

The class that I would like to add the method to does not extend the class where the method comes from.

I've tried:

MyMethod p = new MyMethod;

When I do this I get 'cannot resolve symbol 'MyMethod'

user979587
  • 269
  • 3
  • 14
  • it should be `MyMethod p = new MyMethod();` And if its a method then may be `MyClass p = new MyClass();` then `p.myMethod(args);` – Harry Joy Oct 24 '11 at 05:52
  • see http://stackoverflow.com/questions/4848820/calling-another-method-from-the-main-method-in-java/4848886#4848886 for example. –  Oct 24 '11 at 05:52
  • I would have though the error would be a syntax error because of the missing argument list just before the final semicolon. – Ray Toal Oct 24 '11 at 05:52
  • so i need to import the whole class then, and then use the method. – user979587 Oct 24 '11 at 05:59

2 Answers2

2

The statement MyMethod p = new MyMethod

is syntactically incorrect. If MyMethod is a class , and if you want to create an instance of it to call any method of it :

Then the correct syntax to instantiate would be :

  MyMethod p = new MyMethod(); 

Then you need to implement methods and call it with the newly created instance p.

If you are asking about calling a method from different class existing in a different package, you 1st have to import that class in your MyMethod class, then have to create an instance of that class, or cast with that class to be able to call the method.

Swagatika
  • 3,376
  • 6
  • 30
  • 39
  • Cool, so you can't just create an instance of a method in another class but you need to create an instance of that class first and then initialise the method. – user979587 Oct 24 '11 at 06:05
  • **you need to create an instance of that class first and then initialise the method**.... its not initializing a method, its calling a method else you are correct. – Harry Joy Oct 24 '11 at 06:08
  • "you can't just create an instance of a method" : This is a WRONG statement. Instance is created ALWAYS from a Valid Class, never from a Method. – Swagatika Oct 24 '11 at 06:15
  • crap, getting a null pointer and its pointing to the method in the external class, i'm giving it args so don't know whats wrong. – user979587 Oct 24 '11 at 06:16
  • @user979587: then **read** the stack trace and check the lines it mentions. If you can't find the problem then **post** the stack trace and point us at the lines it mentions. – Joachim Sauer Oct 24 '11 at 06:36
0

May be the method is private . U cannot call private method in other class.

This is simple:

Class A{

  public void methosAA(){

  }

}


Class B{

A a=new A();

 public static void main(){
    a.methosAA();
}

}
vikas27
  • 563
  • 5
  • 14
  • 36