Header Ads

Access Modifiers in java | Public Modifier in java

Public Modifier in java

Public Modifier in java



If a class declared with public modifier then we can access that class from anywhere. With in the package or outside the package.



Example:


Program l:


package pack1;

public class Abc

{

public void methodOne()

 {

    System.out.printin("Abc class methodone is executed");

 }

}

Compile the above Program:

   javac  Abc.java






Program 2:


package pack2;

import pack 1. Abc;

class Test1

{

public static void main(String args[])

{

  Abc a=new Abc();

  a.methodOne();

}

}


OUTPUT:

 javac Testl java  -->(run on cmd)

 java pack2.Test1      -->(run on cmd)

Abc class methodone is executed.   -->(output on cmd)


If class Abc is not public then while compiling Testl class we will get compile time error saying pack1.Abc is not public in packl; cannot be accessed from outside package.




No comments

Note: Only a member of this blog may post a comment.