Showing posts with label Encapsulation in Java step by step in details. Show all posts
Showing posts with label Encapsulation in Java step by step in details. Show all posts

Encapsulation in Java in Details Step by Step



OOPS concepts in Java

Java tutorials for beginners

Java basics concepts

Java Objects and Classes

What is Inheritance in Java?

What is Abstraction in Java?

What is Interface in Java?

What is Abstract Class in Java?

What is Polymorphism in Java?

What is Encapsulation in Java?

Java programming example

How Java Program Work?

Hello World in Java

Java basics for beginners



Encapsulation:


Encapsulation is the process of wrap the data and code into single unit. The variables of a class will be hidden from other classes, and can be accessed by methods of their current class.

Make encapsulation in following way.

1. Declare variables as private.
2. Declare public setter and getter methods to access or modify the value.


Example:

public class Employee {
        private int id;
        private String name;
        private int age;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
       } 
}