public, private, package, protected in Java

In Java, class members can be declared with public, private, protected, or nothing. If you need to access a member from another package (even from a derived class)using obj.membername, the member must be declared as public.  But in derived class in another package, you can use the member directly if the member is public or protected but cannot use the member directly if the member is declared without an access modifier(error:cannot find symbol) because derived class in different package does not inherit the member without an access modifier.

//App.java
package fruit;

public class App 
{
  String a="aa";
  void fun()
  {
    System.out.println("in App");
  }
}

class App1
{
  String a="aa";
  void fun()
  {
    App app=new App();
    app.fun();
    
    System.out.println("in App1");
  }
}

class App2 extends App
{
  String a="aa";
  void fun1()
  {
    App app=new App();
    app.fun();
    fun();
    
    App2 app2=new App2();
    app2.fun();
    System.out.println("in App1");
  }
}

 

//Test.java
import fruit.App;
class Test extends App
{
  String a="aa";
  public static void main(String[] args)
  {
    App app=new App();
    //app.fun();
    //fun();
    System.out.println("hello");
  }
  void fun2(/*App app*/)
  {
    fun();//error:cannot find symbol
    Test app=new Test();
    app.fun();//error: cannot find symbol
    App ap=new App();
    ap.fun();//error:fun() is not public
  }
}

If you declare a member with private, the member can only be accessed within the class itself. Other classes, whether they are derived classes or not, whether they are in the same package or not, cannot access the member using any method.

If you define a member with public, the member can be accessed anywhere(in the class, derived classes in the same package or different package, other classes in the same package or different packages). In derived classes, it can be accessed by the member name, parentobj.membername, or subclassobj.membername.

If you don’t add an access modifier when declaring a member, the member can be accessed by non-derived classes in the same package using obj.membername, can be accessed by derived classes in the same package using parentclassobj.membername, subclassobj.membername, and membername.  The member cannot be accessed from non-derived classes in different packages using obj.membername, cannot be accessed by derived classes in other packages using membername, subclassobj.membername, parentclassobj.membername. In other words, the member is totally invisible(or not accessible) in other packages; the member behaviors like a public member for classes in the same package. Note that members without an access modifier are not like those in C++, which are private members by default and cannot be accessed outside the class.

For members declared with protected, please refer to this post.

Comments are closed, but trackbacks and pingbacks are open.