-
Access ModifierStaticPL/JAVA 2020. 2. 23. 22:50
1. Overview
2. Example
2.1 private
class A{ private int data=40; private void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error } }
class A{ private A(){}//private constructor void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A();//Compile Time Error } }
2.2 default
//save by A.java package pack; class A{ void msg(){System.out.println("Hello");} }
//save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A();//Compile Time Error obj.msg();//Compile Time Error } }
2.3 protected
//save by A.java package pack; public class A{ protected void msg(){System.out.println("Hello");} }
//save by B.java package mypack; import pack.*; class B extends A{ public static void main(String args[]){ B obj = new B(); obj.msg(); } }
Output:Hello
2.4 public
//save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} }
//save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } }
Output:Hello
2.5 Java Access Modifiers with Method Overriding
If you are overriding any method, the overridden method (i.e. declared in a subclass) must not be more restrictive.
class A{ protected void msg(){System.out.println("Hello java");} } public class Simple extends A{ // void msg(){System.out.println("Hello java");}//C.T.Error. This is invalid protected void msg(){System.out.println("Hello java");} // This is valid public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } }
3. Reference
'StaticPL > JAVA' 카테고리의 다른 글
synchronized (0) 2020.02.27 Atomic Variables (0) 2020.02.26 Is-A and Has-A Relationship in Java (0) 2020.02.05 Boxing, unboxing, and autoboxing (0) 2019.09.27 Functional (0) 2019.08.27