Scientech Easy OMG! The Best Programming practice for Encapsulation Ever! | Scientech Easy

Sunday, June 17, 2018

OMG! The Best Programming practice for Encapsulation Ever!

programming,encapsulation,object oriented programming,c++ programming,programming tutorial

Encapsulation Programming Practice:

Program 1: In this program, we will set one field as private in the class Number. So the field can be accessed only within the class and no anyone can access from outside the class. After that, we will use public setter and getter methods to set and read the value of the variable or field. By doing this, we are hiding the field and providing its implementation from outside the class. This whole process is called Encapsulation.

    Step1: Create a package as 'numberTest' and make a class 'Number'. package numberTest; public class Number{ Step2: Declare fields/variables as private. private int y; Step3: Create the public getter methods for each private variables. public int get(){ return y; } Step3: Create the public setter methods for each private variables and declare the parameter. public void set(int y){ this.y=y; } } Step4: Create another class EncapTest. public class Encaptest{ public static void main(String[] args){ Step5: Create the object of class Number using the new keyword. Number n=new number(); // Here, n is a reference variable of Number and pointing to the object of class Number. Step6: Now call the setter method and set the value of the variable. n.set(6) Step7: Call getter method to read the value of variables int num=n.get(); Step8: Print the output. System.out.println(num); } }
    Output: 6
In the above program, the variable y is made private. This variable can be accessed and manipulated only using set() and get() method. Thus we can say that here the variable y and the functions get() and set() are bonded together which represents Encapsulation.

Common mistakes when implementing the getter and setter method:
Consider the above code snippet, If the variable y is declared as public then it can be accessed using dot(.) operator directly and making the setter and getter useless. So always declare more restrictive access modifiers such as protected and private.
    protected String name; private int num;
Follow all above steps to make the coding snippet of Encapsulation easy.

Program 2: Let us understand one more program. In this example, we will make a class 'Rectangle' and declare the variable length and breadth as private. One Constructor will be used for initializing the value of variables. 
When the object is created then the constructor will be called and the default values of the instance variable will be assigned.

    Package rectangleArea; public class Rectangle{ // Declare the variable as private. private int length; private int breadth; // Declare the constructor Rectangle and defines the parameter of constructor. Rectangle(int length, int breadth){ this.length=length; this.breadth=breadth; } // Create the getter methods for private variable. public int getLength(){ return length; } public int getBreadth(){ return breadth; } // Create the setter method for the private variable and define the parameter. public void setLength(int length){ this.length=length; } public void setBreadth(int breadth){ this.breadth=breadth; } }
Now create another class 'RectangleTest'.

    package rectangleArea; public class RectangleTest{ public static void main(String[] args){ // Create the object of class Rectangle and assign the values of the parameter used in the constructor. Rectangle rt=new Rectangle(20,30); // Call the getter method to read the value of variable because we cannot read the value directly due to privacy. int lth=rt.getLength(); int bth=rt.getBreadth(); // Calculate area of the rectangle and print it on the console. int Area=lth*bth; System.out.println(Area); //, let's update the new value of the variable using the setter method. rt.setLength(50); rt.setBreadth(60); // Call the getter method to read the updated value. int ln=rt.getLength(); int br=rt.getBreadth(); int Ar=ln*br; System.out.println(Ar); } }
    Outputs: 600 3000
Program 3: In this program, we are creating a class Student and declare the variables stdName, stdRollNo, and stdId as private and follow all the above steps.

    package schoolStudent; public class Student { // Step 1: Declare the variable private which you want. private String stdName; // private field. private int stdRollNo; private int stdId; // Step 2: Apply the public getter method for each private vairable. public String getStdName(){ // private field accessed inside public method. return stdName; } public int getStdRollNo(){ return stdRollNo; } public int getStdId(){ return stdId: } // Step 3: Apply the public setter method for each private variable. public void setStdName(String name){ stdName=name; } public void setStdRollNo(int rollNo){ stdRollNo=rollNo; } public void setId(int id){ stdId=id; } }
    public class EncapTest{ public static void main(String[][] args){ // Step 4: Create the object of class Student by using the new keyword. Here, obj is the reference variable of class student and pointing to the object of the class student. Student obj=new Student(); // Step 5: Call setter method and set the value of variables. obj.setStdName("Kiran"); obj.setStdRollNo(4); obj.setStdId(12345); // Step 6: Call getter method to Read the value of variables and print it. System.out.println("Student's Name: " +obj.getStdName()); System.out.println("Student's Roll no.: " +obj.getStdRollNo()); System.out.println("Student's Id: " +obj.getStdId()); } }
    Output: Student's Name: Kiran Student's Roll no.: 4 Student's Id: 12345
Program 4: If you do not define the setter method in the class then the fields can be made read-only. Let's consider one example. In this example, we are creating a class 'Player' in which all the fields are declared as private and a constructor is also declared for initializing the parameter.

    package player; public class Player; // Declare the variable as private. private String pName; private int pAge; private String gameType; // Create a construtor and initialize the three parameters pName, pAge, and gameType. public Player(String pName, int pAge, String gameType){ this.pName=pName; this.pAge=pAge; this.gameTypte=gameType: } // Create the getter method for the private variables. public String getPName(){ return pName; } public int getPAge(){ return pAge; } public String getGameType(){ return gameType; } }
    package player; public class PlayerTest{ public static void main(String[] args){ // Create the object of the class Player using new Keyword and initialize the value of the parameters. Player ply=new Player("Sachin", 40, "Cricket"); // Call the getter method to read the value of the variables. String plyName=ply.getPName(); int plyAge=ply.getPAge(); String plyGameType=ply.getGameType; System.out.println("Player's Name: " +plyName); System.out.println("Player's Age: " +plyAge); System.out.println("Player's Gametype: " +plyGameType); } }
    Output: Player's Name: Sachin Player's Age: 40 Player's Gametype: Cricket 
Program 5: If you do not define the getter method in the class then the fields can be made write-only. Let's consider one more example to make write-only. In this example, we will follow all the above steps and we will create a method, not constructor because we cannot send directly the values of the parameter using the constructor. Here, we will set the values using setter method.

    package school; public class Student { // Declare the variables as private. private String name; private int phyMarks; private int chemMarks; private int bioMarks; // Create the setter method for all private variables. public void setName(String name){; } public void setPhyMarks(int phyMarks){ this.phyMarks=phyMarks; } public void setChemMarks(int chemMarks){ this.chemMarks=chemMarks; } public void setBioMarks(int bioMarks){ this.bioMarks=bioMarks; } // Create a method to print the output such as Student's Name, Marks in three subjects and percentage. void marksRead(){ System.out.println("Student's Name: " +name); System.out.println("Marks in Physics: " +phyMarks); System.out.println("Marks in Chemistry: " +chemMarks); System.out.println("Marks in Biology: " +bioMarks); int Totalmarks=phyMarks+chemMarks+bioMarks; float percentage=(Totalmarks*100)/300; System.out.println("Percentage of PCB: " +percentage); } }
    package school; public class StudentMarks { public static void main(String[] args) { Student st=new Student(); // Call the setter method and declare the value of the variables. st.setName("Vivek"); st.setPhyMarks(85); st.setChemMarks(75); st.setBioMarks(90); // Call the method to get the output. st.marksRead(); } }
    Output: Student's Name: Vivek Marks in Physics: 85 Marks in Chemistry: 75 Marks in Biology: 90 Percentage of PCB: 83.33
Final words:

I hope this article will help you to practice the Encapsulation Programming. If you practice all the programs then definitely the concepts of Encapsulation will be cleared to you.
                                                                           Click here Encapsulation in Java Tutorials.