In this blog we can know about why we go for JAVA?. Java is a language known for object oriented features and its network support. Here object oriented is achieved by three concepts
- Encapsulation
- Inheritance
- Polymorphism but Java is not pure object oriented
Encapsulation, we had come across the word "capsule" many times in our life. capsule is nothing but a outer protection(cover) used to protect the something from external factors. example the medicines usually come with a capsule to protect the chemicals inside it. Similarly the encapsulation is used to wrap the code or data from intruders in order to ensure its security.
- Default
- Private
- Protected
- Public
Default
It assigned by default also referred as package(explained later). i.e. the default modifier can be accessed within a class, subclass of the same package, different class but same package but not the class or subclass of different package.
Private
Most secure modifier which can be only within class even with another class is not possible.
Protected
This modifier can be accessed within a class, subclass, class of same package, subclass in different package but not the class in different package.
Public
This most free modifier which means it can be accessed everywhere.
In additional java provide Serializable, which can be used in networks where the objects can be accessed via network. you can find many in collections(explained later).
Encapsulation is achieved with getter and setter methods.
- class A{
- private int data;
- public int data1;
- private int password=9899;
- public int password1=9899;
- public void set_data(int age){
- if(age>18){
- data = a;
- data1=a;
- }
- public int send_data(int pass){[
- if(pass==password){
- return data;
- }
- if( pass==password1){
- return data;
- }
- }
- }
- class Main{
- public static void main(String sde[]){
- A obj = new A();
- obj.password=66;--------------------//-cannot be modified.
- obj.password1=66;--------------------//----can be modified.
- obj.data=17;----------------------------//cannot be modified.
- obj.data1=17;---------------------------//---can be modified.
- obj.set_data(54);
- obj.send_data(66);----/first if can't be send but second if send the data.
- }
- }
The above example should store only the age which is greater than 18 and the data is send only when the user knows the password. without the modifiers the data can be stolen. its is explained above, the password and data is protected but password1 and data1 is not.
Try this example....
Try this example....
I hope you could get some idea about encapsulation...any queries comment below and do subscribe for more blog's
Comments
Post a Comment