Private Vs Protected in Java [In-Depth Tutorial]


JAVA

Author: Bashir Alam
Reviewer: Deepak Prasad

In Java, methods are the building blocks of classes, which allow us to encapsulate functionality within an object-oriented paradigm. Java provides several access modifiers, including public, private, and protected, that determine how the method can be accessed from within and outside of the class. This article will focus on the differences between private and protected methods in Java, including their access levels and use cases.

 

What is a private method in Java?

In Java, a private method is a method that is declared with the private keyword. This means that the method can only be accessed from within the same class in which it is declared. Other classes cannot call a private method directly.

The main purpose of private methods is to encapsulate certain functionality or implementation details within a class. By making a method private, we can ensure that the method is only accessible by code within the same class. This helps to hide certain implementation details and makes the class easier to maintain and modify.

One common use case for private methods is to perform a complex calculation or operation within a class. For example, if we have a class that calculates the square root of a number, we may want to encapsulate that calculation within a private method. This would allow us to hide the details of the calculation and provide a simple interface for other classes to use.

Here's an example of a class with a private method:

public class MyClass {
  private int calculateSum(int a, int b) {
    return a + b;
  }

  public int getSum(int a, int b) {
    return calculateSum(a, b);
  }
}

In this example, the calculateSum method is private and can only be accessed within the MyClass class. The getSum method is public and provides a simple interface for other classes to get the sum of two numbers. The getSum method calls the calculateSum method to perform the calculation.

By using a private method to encapsulate the calculation, we can ensure that other classes cannot access the calculation directly. This helps to keep the implementation details hidden and makes the class easier to maintain and modify.

 

Access modifiers for private methods

Access modifiers in Java are keywords that are used to specify the level of access that other classes have to a particular class, method, or field. In the case of private methods, the private keyword is used as an access modifier. When a method is declared private, it can only be accessed within the same class in which it is declared. This means that other classes, including subclasses, cannot call a private method directly.

Here's an example of a private method:

public class MyClass {
    private void doSomething() {
        // Method implementation
    }
}

In this example, the doSomething() method is declared as private. This means that it can only be called from within the MyClass class. If another class were to try to call this method, it would result in a compilation error.

One common use case for private methods is to encapsulate behavior that should not be accessed by other classes. For example, if we have a class that performs a complex calculation, we may want to encapsulate that calculation in a private method so that other classes cannot access it directly.

 

Example of Private method in Java

Let us take an example of a Private method in Java and try to understand how it works.

public class Example {
   private int number;

   public Example(int number) {
      this.number = number;
   }

   public int getNumber() {
      return number;
   }

   public void setNumber(int number) {
      this.number = number;
   }

   public void printNumber() {
      System.out.println("The number is: " + number);
      System.out.println("The square of the number is: " + squareNumber());
   }

   private int squareNumber() {
      return number * number;
   }
}

In this example, we have a class called Example with a private field called number. We also have a public getter and setter method for this field.

The interesting part is the printNumber() method, which calls a private method called squareNumber(). This method calculates the square of the number field and returns it.

Now, let's create an instance of the Example class and call the printNumber() method:

Example example = new Example(5);
example.printNumber();

Output:

The number is: 5
The square of the number is: 25

As you can see, the printNumber() method is able to call the private squareNumber() method and use its result without exposing the implementation details to other classes.

 

What is a protected method in Java?

A protected method is a method that can be accessed within the same class and any subclasses of that class. This means that subclasses can call a protected method directly, but other classes cannot.

Protected methods are useful when we want to provide a certain level of access to subclasses but still want to keep the method hidden from other classes.

 

Access modifiers for protected methods

The access modifier for a protected method is the keyword protected. This keyword must be placed before the method declaration to indicate that the method is protected.

For example, let's say we have a class called Animal with a protected method called eat():

public class Animal {
    protected void eat() {
        System.out.println("The animal is eating.");
    }
}

In this example, the eat() method is declared as protected. This means that it can be accessed within the Animal class as well as any subclasses of Animal.

 

Accessing protected methods

To access a protected method from a subclass, we can simply call the method as if it were a public method. Here's an example:

public class Dog extends Animal {
    public void bark() {
        System.out.println("The dog is barking.");
        eat(); // calling the protected eat() method
    }
}

In this example, we have a subclass of Animal called Dog. The Dog class has a public method called bark() that also calls the protected eat() method of the Animal class.

 

Example of Protected class in Java

Let us now take a full example of a protected class in Java which will help us to understand the concept behind it.

public class Animal {
  protected void makeSound() {
    System.out.println("The animal makes a sound");
  }
}

public class Dog extends Animal {
  public void makeSound() {
    System.out.println("The dog barks");
  }
}

public class Main {
  public static void main(String[] args) {
    Animal animal = new Animal();
    animal.makeSound();
    
    Dog dog = new Dog();
    dog.makeSound(); 
  }
}

Output:

The animal makes a sound
The dog barks

In this example, we have an Animal class with a protected method called makeSound(). We also have a Dog class that extends Animal and overrides the makeSound() method with its own implementation.

In the Main class, we create an instance of Animal and call its makeSound() method, which outputs "The animal makes a sound". This is because makeSound() is protected and can only be accessed within the Animal class and any subclasses.

We also create an instance of Dog and call its makeSound() method, which outputs "The dog barks". This is because Dog overrides the makeSound() method with its own implementation, and makeSound() is protected so it can be accessed by the subclass.

 

Differences between private and protected methods

Here are some of the major differences between private and protected methods in the Java programming language.

Accessibility

The main difference between private and protected methods is their accessibility. Private methods are only accessible within the same class in which they are declared. Other classes, including subclasses, cannot access private methods directly. This means that private methods are entirely hidden from other classes and can only be called from within the class where they are declared.

Protected methods, on the other hand, are accessible within the same class and any subclasses of that class. This means that subclasses can call protected methods directly, but other classes, including classes in different packages, cannot access protected methods. Protected methods provide a level of access to subclasses while still keeping the method hidden from other classes.

Inheritance

Private methods cannot be overridden in subclasses. This means that even if a subclass declares a method with the same name and signature as a private method in the parent class, the subclass's method does not override the parent class's method. Instead, the subclass has two separate methods with the same name and signature.

Protected methods, on the other hand, can be overridden in subclasses. This means that if a subclass declares a method with the same name and signature as a protected method in the parent class, the subclass's method overrides the parent class's method. The subclass can provide its own implementation of the protected method while still having access to the parent class's implementation through the super keyword.

Encapsulation

Both private and protected methods are important for encapsulating behavior within a class. Private methods allow us to hide certain implementation details from other classes. This can help to prevent other classes from accessing or modifying the internal state of an object in unexpected ways. By encapsulating behavior in private methods, we can ensure that the behavior can only be called from within the same class and is not exposed to other classes.

Protected methods allow us to provide a certain level of access to subclasses while still keeping the method hidden from other classes. This can help to ensure that the behavior provided by the protected method is only used in the way intended by the parent class. By encapsulating behavior in protected methods, we can provide a level of access to subclasses while still controlling how the behavior is used.

 

Summary

In Java, private and protected are access modifiers that control the visibility and accessibility of class members, including methods. A private method is only accessible within the class where it is defined, while a protected method is accessible within the class and its subclasses.

Private methods are often used for implementing internal logic within a class, while protected methods are used for defining behavior that can be inherited and overridden by subclasses.

The main difference between private and protected methods is their visibility within a class hierarchy. Private methods are only visible within the class where they are defined, while protected methods are visible within the class and its subclasses. This means that protected methods can be used to define behavior that can be inherited and overridden by subclasses, while private methods are limited to the class where they are defined.

Best practices for using private and protected methods in Java include minimizing the use of protected methods, avoiding excessive use of private methods, and using protected methods to define behavior that can be inherited and overridden by subclasses.

 

Further Readings

Protected method in java
private method in java

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment