In this example I create a class called Square. It has a public method called display_area. This has to call a private method called calculate_area before it can display the result. Private methods are only accessible from within the class which contains them:
andrew@UBUNTU:~/Java$ cat Square.java
public class Square
{
double width;
double area;
public void display_area()
{
calculate_area();
System.out.println("Area = " + area);
}
private void calculate_area()
{
area = width * width;
}
}
andrew@UBUNTU:~/Java$ javac Square.java
andrew@UBUNTU:~/Java$
I create a program to define a square and display its area (I have shown you a similar example already):
andrew@UBUNTU:~/Java$ cat SquareExample1.java
class SquareExample1
{
public static void main(String args[])
{
Square my_square = new Square();
my_square.width = 5;
my_square.display_area();
}
}
andrew@UBUNTU:~/Java$ javac SquareExample1.java
andrew@UBUNTU:~/Java$ java SquareExample1
Area = 25.0
andrew@UBUNTU:~/Java$
However, when I try to execute the calculate_area method directly from outside the class, Java returns a compilation error as the method concerned is private:
andrew@UBUNTU:~/Java$ cat SquareExample2.java
class SquareExample2
{
public static void main(String args[])
{
Square my_square = new Square();
my_square.width = 5;
my_square.calculate_area();
}
}
andrew@UBUNTU:~/Java$ javac SquareExample2.java
SquareExample2.java:7: calculate_area() has private access in Square
my_square.calculate_area();
^
1 error
andrew@UBUNTU:~/Java$