Darpan Kulkarni
Darpan Kulkarni

Reputation: 1400

Access method from user defined package in java

Here is my package arithmatic inside which a file called arith.java

package arithmatic;

 public class arith{

     public int add(int a, int b){
     return(a+b);
     }
}

and outside the arithmatic package a file packagedemo.java

import arithmatic.*;
public class packagedemo{

public void disp(int a, int b){

    System.out.println("Addition is : "+ add(a, b));
}

public static void main(String args[]){

    packagedemo pd=new packagedemo();
    pd.disp(20,10);
}
}

after compiling it gives me error as,

packagedemo.java:6: cannot find symbol
symbol  : method add(int,int)
location: class packagedemo
            System.out.println("Addition is : "+ add(a, b));

I really dont understand why this error occurs any solution please?

Upvotes: 0

Views: 372

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 122026

You need to create instance of arith since the method add is an insntance member of that class.

public void disp(int a, int b){
    Arith art= new Arith();
    System.out.println("Addition is : "+ art.add(a, b));
}

As a side note please follow java naming conventions ,Class name starts with capital letter.

public class Arith{

I guess you are checking the package level accesses, in that case you are looking for protected modifier for your add() method. So when you create instance of Arith insntance in other packages you won't have access to that protected member. Now it is public so, you can use it.

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

By simply importing a class, you cannot directly access a class member method like this

add(a, b)

You first need to create and instance of your arith class and then call add method using that instance. Something like this:

public void disp(int a, int b){

    arith arithObj = new arith();
    System.out.println("Addition is : "+ arithObj.add(a, b));
}

Upvotes: 1

Related Questions