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.
private int date;
public void validate(int d1)
if(d1 > 0 && d1 < 32)
date = d1;
System.out.println("Yes, your birth date is " + date + " and is valid");
System.out.println("Sorry, your birth date is " + d1 + " and is invalid");
public class BirthDate
public static void main(String args)
CheckDemo cd1 = new CheckDemo();
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)