Encapsulation in java

Encapsulation:

  • Data encapsulation is used to hide the implementation details from users.
  • If a data member is private it means it can only be accessed within the same class. 
  • No outside class can access private data member (variable) of other class.

Syntax:

  1. class class_name

    {

    private data_members;

    public methods()

    {

    }

    }

Example program:
  1. class Account {

        private int account_number;

        private int account_balance;

     

        public void show_Data() {

            account_number=13456;

            account_balance=5000;

            System.out.println("Before deposit of "+"account XXXXX"+account_number+" number of balance :"+account_balance);

        }

     

        public void deposit(int a) {

            if (a < 0) {

                System.out.println("Given amount is wrong...");

            } else

                account_balance = account_balance + a;

            System.out.println("After deposit of current balance :"+account_balance);

        }

    }

     

    class Encapsulation{

        public static void main(String args[])

        {

            Account ac=new Account();

            ac.show_Data();

            ac.deposit(200);

        }

    }

Output:
Share:

No comments:

Post a Comment

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me