简体   繁体   中英

How to access a method of another class in another file which is in same package in java?

Myclass.java

package mypackage;


import java.util.*;
public class Myclass{
    public static void add(int a,int b){
            System.out.println(a+b);
    }
    public static void main(String[] args){
        System.out.println("success");
    }
}

Good.java

package mypackage;


public class Good{
    public static void main(String [] args){
        Myclass obj = new Myclass();
        obj.add(2,3);
    }
}

how to access add method in Myclass in Good class?

Error I am encountering while compiling

Good.java:6: error: cannot find symbol
                Myclass obj = new Myclass();
                ^
  symbol:   class Myclass
  location: class Good
Good.java:6: error: cannot find symbol
                Myclass obj = new Myclass();
                                  ^
  symbol:   class Myclass
  location: class Good
2 errors

Well, The code is running perfectly in my system but there are some points for your cross verification:

  1. I think Myclass.java file is not able to be recognized in Good.java class. So, please check that all *.java files are in the same folder.
  2. It is not required to use the import java.utill. ;* in Myclass.

I hope it will be helpful. Note: Any issue or suggestion finding, please let me know in coomment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM