Private concrete methods in Abstract class

Moderator: admin

Post Reply
yrelhan
Posts: 5
Joined: Wed Jun 07, 2017 3:13 am
Contact:

Private concrete methods in Abstract class

Post by yrelhan »

The official Java docs says "However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods"

How to call the private methods in an abstract class?

Also can an abstract class have private instance variables?

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Private concrete methods in Abstract class

Post by admin »

Here is an example:

Code: Select all

abstract class Animal{
  private int id = 0; //private instance variable
  private void log(){  
     System.out.println("in private do x");
  }
  public void doX(){
    log(); //call private method
  }
}
If you like our products and services, please help us by posting your review here.

poojagite
Posts: 1
Joined: Fri Nov 16, 2018 2:09 am
Contact:

Re: Private concrete methods in Abstract class

Post by poojagite »

An abstract class is permitted to have both concrete and abstract methods. In abstract class, no method (either concrete or abstract) can be private. The reasons are very simple and when known looks as of common sense.

Let us make a list to remember.

Abstract methods in an abstract class cannot be private but can be of specifiers public, protected or default.
Similarly, any class cannot be protected or private (can be only public or default). So by this rule, an abstract class cannot be private.
Abstract method or concrete method in abstract class can be protected (a program is available at the end).
As a general rule of Java, the private methods cannot be inherited by subclass. When not inherited, how the abstract methods can be given body (or overridden or implemented) by subclass.
When a method is private, the sub classes can’t access it, hence they can’t override it.

Post Reply

Who is online

Users browsing this forum: No registered users and 19 guests