0

I am familier with other languages.But i am learning java now. I was reading the access modifiers . I found that only public class can be accessed from outside. And the [default] class cant not be accessed from outside. But as i have written some simple code i cam access the non public class from outside:

Add.java

class Add{
    int a(int x, int y)
    {
        return x+y;
    }
}

MyClass.java

public class MyClass {
    public static void main(String args[]) {
      Add obj= new Add();
      int sum= obj.a(10,20);
      System.out.println("Sum of x+y = " + sum);
    }
}

OUTPUT>>>

Sum of x+y = 30

So please someone explain this for me? I want to know how this is happening! Thanxx in advance.

user222203
  • 21
  • 5
  • Are these classes in the same package? – rgettman Aug 22 '19 at 19:25
  • i have given all i have done . i created those two java files ,nothing else – user222203 Aug 22 '19 at 19:26
  • @user222203 Then both classes are automatically part of the unnamed package, which makes them accessible to each other given that package-private is the default access modifier in Java. – Keiwan Aug 22 '19 at 19:27
  • The answer is: it is the way it is, because that is the design of the language. There is no deeper meaning behind it. You can read all about the access modifiers and their behaviour in a tutorial, e.g. this [Oracle tutorial on Controlling Acces to Member of Classes](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html). – Turing85 Aug 22 '19 at 19:28
  • @Keiwan your comment might be the answer , that they are automatically treating each other as same package, as i have no given any package name.. – user222203 Aug 22 '19 at 19:33

1 Answers1

0

As you maybe know, they are 4 access modifiers in Java - default, private, protected and public. The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package. I assume, that both of the classes - Add.class and MyClass.class are in the same package, try to separate them and you will see that you can't accessed from outside.

s.3.valkov
  • 75
  • 3