Encapsulation & Constructor In Java

Encapsulation In Java

  1. Wrapping of data member(variables) and member function(methods) into single unit(class).
  2. Class is also an encapsulation because it has data members and member functions.

Encapsulation

  1. Is a way to hide the data and providing access to the data by methods.
  2. To Hide data/variable declare it with private access modifier.
  3. To access hidden data, have to provide setter(to set data) and getter(to get data) methods.
  4. Advantage of Encapsulation
    1. Can achieve loose coupling.
    2. Can added new code easily without effecting others.
    3. Can update existing code easily which will applicable to other locations also.
    4. Can be achieve Data Hiding.

 

Constructor In Java

  1. Constructor is use to initialize the instance variable.
  2. 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.
  3. If you are writing constructor inside class manually then java will not provide any constructor.
  4. Rules to create constructor
    1. Constructor name must be same as class name.
    2. Constructor do not have return data type.
    3. Constructor can be create by any access modifier like private, public, protected, default.
    4. There can be more than one constructor available inside class.
    5. 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

 

Share This Information To Your Friends and Your College Group’s, To Help Them !