Suppose you want to set the value of id which should be greater than only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members. The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.
Let's see the simple example of encapsulation that has only one field with its setter and getter methods. Now, you can't get the value of the college, you can only change the value of college data member. Let's see another example of encapsulation that has only four fields with its setter and getter methods.
JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services. Please mail your requirement at [email protected] Duration: 1 week to 2 week. Java Training Basics of Java. Abstract class Interface Abstract vs Interface. Package Access Modifiers Encapsulation. Compile By: javac -d. Next Topic Object class in java. Reinforcement Learning.
R Programming. React Native. We just launched W3Schools videos. Get certified by completing a course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:. Report Error. Your message has been sent to W3Schools. W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content.
What is Encapsulation in Java? Getter and Setter in Java Getter and Setter in Java are two conventional methods used to retrieve and update values of a variable. Report a Bug. Previous Prev. Next Continue. Home Testing Expand child menu Expand. SAP Expand child menu Expand.
Web Expand child menu Expand. Must Learn Expand child menu Expand. Big Data Expand child menu Expand. Live Project Expand child menu Expand. AI Expand child menu Expand. Toggle Menu Close.
0コメント