Why is there a private access modifier in an abstract class in Java, even though we cannot create an instance of an abstract class? -


i know not coding practice declare method private in abstract class. though cannot create instance of abstract class, why private access modifier available within abstract class, , scope of within abstract class? in scenario private access specifier used in abstract class?

check out code vehicle class abstract , car extends vehicle.

package com.vehicle;  abstract class vehicle {   // scope of private access modifier within abstract class, though  method below cannot accessed??   private void onlights(){    system.out.println("switch on lights");   }    public void startengine(){    system.out.println("start engine");   }  } 

within same package creating car class

package com.vehicle; /*  * car class extends abstract class vehicle  */ public class car extends vehicle {   public static void main(string args[]){   car c =  new car();   c.startengine();   // startengine() can accessed   }  } 

since abstract class can contain functionality (as opposed interface) can have private variables or methods.

in example might like

 public void startengine(){    injectfuel();    ignitespark();    // etc. understanding of engines limited @ best    system.out.println("start engine");  }   private void injectfuel() {}  private void ignitespark() {} 

that way can spread of work other methods (so don't have 1000 line startengine method), don't want children able call injectfuel separately since doesn't make sense outside context of startengine (you want make sure it's used there).

or more might have private method gets called in several other public methods, different parameters. way avoid writing same code twice or more in each of public methods, , grouping common code in private method makes sure children don't access (like couldn't call part of public method before). this:

 public void startengine() {    dishargebattery(50);    system.out.println("start engine");  }   public void startradio() {    dischargebattery(20);  }   private void dischargebattery(int value) {    battery.energy -= value; //battery should private field.  } 

this way methods can have access battery, children shouldn't mess it, , don't write same line (battery.energy -= value) in both of them. take note though, these simple examples, if dischargebattery 500 line method, writing in both other methods hassle.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -