Page 1 of 1

Private concrete methods in Abstract class

Posted: Wed Jun 14, 2017 2:29 pm
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?

Re: Private concrete methods in Abstract class

Posted: Thu Jun 15, 2017 2:28 am
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

Re: Private concrete methods in Abstract class

Posted: Wed Nov 21, 2018 4:44 am
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.