Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Private Method

Posted By: Iqbal Bashara     Category: Java     Views: 12905

This article explains about private method in java with examples.

Private method is a which can be invoked by code in the same class. It is not inherited by subclasses.

Syntax of Private Method

class clsName
{
     // Variable declaration
 
     // Constructor

     // Method
     private rtype mthName(params)
     {
            // Body of private method
     }
}

clsName is a valid identifier in java. It is a class name.
abstract is a keyword to define that method an abstract method.
rtype is return type of a method.
mthName is a method name and valid java identifier.

Example of an Private Method

Example 1 : Program that illustrates the use of private method

class Shape
{
      public static float pi = 3.142f; 
      protected float height;
      protected float width;

      // You cannot  
      private void display() 
      {
              System.out.println("This shape is not defined and cannot calculate area so if you call area method it will always return 0");    
      }

     float area()
      {
             display();
             return (float)0;
      }
}  

class Square extends Shape
{
      Square(float h, float w)
      {
             height = h;
             width = w;
      }

      float area()
      {
            return height * width;
       }
}

class Rectangle extends Shape
{
      Rectangle(float h, float w)
      {
             height = h;
             width = w;
      }

      float area()
      {
             return height * width;
      }
}

class Circle extends Shape
{
      float radius;

      Circle(float r)
      {
             radius = r;
      }

      float area()
      {
            return Shape.pi * radius *radius;
      }
}

class AbstractMethodDemo
{
        public static void main(String args[])
        {
                 Square sObj = new Square(5,5);
                 Rectangle rObj = new Rectangle(5,7);
                 Circle cObj = new Circle(2);

                 System.out.println("Area of square : " + sObj.area());
                 System.out.println("Area of rectangle : " + rObj.area());
                 System.out.println("Area of circle : " + cObj.area());
        }
}

Output
Area of square : 25
Area of rectangle : 35
Area of circle : 12.57
  
Share: 


Didn't find what you were looking for? Find more on Private Method Or get search suggestion and latest updates.

Iqbal Bashara
Iqbal Bashara author of Private Method is from Hyderabad, Pakistan.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!