Public methods and Private Variables

Public methods and Private Variables


What does it mean by Public methods and Private Variables?

Declaring methods as public and variables as private is a programming technique and comes with its own advantages.

We know private variables or methods cannot be accessed by composition (has-a relationship) by another class where as public members can be accessed. A private variable can be accessed through a public method by another class. The advantage is the other class cannot assign wrong values to the variables. The values passed by other class can be checked in a public method and if found correct, assigned to the private variables; else rejected.

Following program illustrates on Public methods and Private Variables.


Public methods and Private Variables
Output screen of Example Public methods and Private Variables

CheckDemo class includes one private variable date and one public method validate(). The validate() method validates the date send by the other class BirthDate. If it is within the range of 1 to 31, it assigns the value to the private variable date, else gives a message.

The other class BirthDate, can not assign to date directly as it is private. So, the BirthDate class accesses the private variable through public method, validate().

Similar explanation is available in Java Private variable accessibility (Private access specifier)

2 thoughts on “Public methods and Private Variables

  1. p.pavan

    class valid
    {
    private int date=20;
    public void checkdate(int d1)
    {
    if(d1>0&&d1<32){
    date=d1;
    System.out.println("your date of birth is" + date + "and is valid");}
    else{
    System.out.println("your date of bith is " + date + "and is not valid");}
    } }
    public class invalid {
    public static void main(String args[]) {
    valid v=new valid();
    v.checkdate(10);
    v.checkdate(32);
    } }
    sir if i write like this it is not taking date value as 20 why??

    1. Rajesh

      because you are assigning new value every time to date
      date=d1;
      for every time date will take the value from d1 which you are passing while calling the checkdate() method

Leave a Reply

Your email address will not be published. Required fields are marked *