0

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?

2 Answers 2

1

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

now it is saying, packagedemo.java:6: cannot find symbol symbol : class artih location: class packagedemo artih ar=new arith(); ^
@Darpan just make sure the class names and package imports are correct.
0

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.

4 Comments

@SURESH ATTA class name is sadly starting with small case arith and not Arith :-)
I saw OP declared class arith, so I corrected it as I cannot do the same mistake again :)
No still in the code you have provided it is Arith art= new Arith();
I provided the code with that correction. Not used the same code given by OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.