+ 1

What the different between public, private and Protected?

8th Oct 2017, 5:27 AM
Heri Cahyono
Heri Cahyono - avatar
2 Answers
+ 5
Public, private and protected are known as the access modifiers. They control the access of a data member , method, constructor or class. Before knowing access modifiers you should know what packages are. Private: This modifier makes a member visible to its class only not outside of its class. eg if a method in a class is declared as private that method cannot be accessed in other classes. If you create an object of that class to access the method it will show an error. eg: public class A { private void name(){ System.out.println("hello"); } } public class B{ A obj= new A(); obj.name(); // will show error } Protected: This access modifier gives more freedom than private. If a member has protected modifier it is accessible within the class as well as within the package. It is also accessible outside the package but only through inheritance. That means if a class has a child class than any member which is protected is accessible in the child class doesn't matter if it belongs to the same package or not. eg: public class A{ protected void name(){ System.out.println("hello"); } } public class B extends A(){ public void nameChild(){ name(); shows no error as name() is inherited } } Public: This gives the maximum freedom. Any member with public modifier is accessible anywhere within the package and outside the package. Default: However there is another modifier default. Not a keyword but if you don't use any access modifiers then it is treated as default which is accessible within the class and within package only.
8th Oct 2017, 5:58 AM
Peerzada Burhan
Peerzada Burhan - avatar