Encapsulation In Java
- Wrapping of data member(variables) and member function(methods) into single unit(class).
- Class is also an encapsulation because it has data members and member functions.
- Is a way to hide the data and providing access to the data by methods.
- To Hide data/variable declare it with private access modifier.
- To access hidden data, have to provide setter(to set data) and getter(to get data) methods.
- Advantage of Encapsulation
- Can achieve loose coupling.
- Can added new code easily without effecting others.
- Can update existing code easily which will applicable to other locations also.
- Can be achieve Data Hiding.
Constructor In Java
- Constructor is use to initialize the instance variable.
- Every class has a constructor, if you do not create any constructor inside class manually then, java will provide constructor by default automatically. This constructor is called as default constructor.
- If you are writing constructor inside class manually then java will not provide any constructor.
- Rules to create constructor
- Constructor name must be same as class name.
- Constructor do not have return data type.
- Constructor can be create by any access modifier like private, public, protected, default.
- There can be more than one constructor available inside class.
- Constructors Cannot be called by using object. Constructors always calls automatically at the time of object creation.
Example :- public class ConstructorDemo { public static void main(String args[]) { Student stud1 = new Student(); System.out.println("Id : " + stud1.id); System.out.println("Name : " + stud1.name); System.out.println("Age : " + stud1.age); Student stud2 = new Student(121, "Abcd", 22); System.out.println("Id : " + stud2.id); System.out.println("Name : " + stud2.name); System.out.println("Age : " + stud2.age); } } class Student { private int id; private String name; private int age; public Student(){ // No Parameterized Constructor id=1; name = "Default Name"; age = 1; } public Student(int i, String n, int a){ // 3 Parameterized Constructor id = i; name = n; age = a; } }
Join Telegram : Click Here
All Full Stack Java Study Material
Job For Fresher