Basic java example program on data encapsulation: package com. So class is the base for encapsulation class is user defined data type in java means by using class we can structure our own programs.
Lest see a example program on class. Instance means dynamic memory allocation. So dynamic memory allocation to class is called object. By using "new" keyword the object will be created dynamically. Class is a template. By using object we will get memory for all variables so that we can use them.
We can use access modifiers to achieve data hiding. For example,. In the above example, we have a private field age. Since it is private , it cannot be accessed from outside the class. In order to access age , we have used public methods: getAge and setAge. These methods are called getter and setter methods. Making age private allowed us to restrict unauthorized access from outside the class. This is data hiding. If we try to access the age field from the Main class, we will get an error.
Course Index Explore Programiz. Java for Loop. Arrays in Java. Interfaces in Java. Java ArrayList. Popular Examples Check prime number. Print the Fibonacci series. Print Pyramids and Patterns. Multiply two matrices. Find the standard deviation. Collection Framework. Multi-threading in Java. Table of Contents. Improve Article. Save Article.
Like Article. Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield. Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of its own class in which it is declared.
As in encapsulation, the data in a class is hidden from other classes using the data hiding concept which is achieved by making the members or methods of a class private, and the class is exposed to the end-user or the world without providing any details behind implementation using the abstraction concept, so it is also known as a combination of data-hiding and abstraction. Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables The program to access variables of the class EncapsulateDemo is shown below: Java.
Output Geek's name: Harsh Geek's age: 19 Geek's roll: Attention reader!
0コメント