how does inheritance work with abstract classes in java -


i writing small pieces of code make sure understand java basics , have following.

package teams1;  public abstract class team1{     private string sport = new string();      public abstract string getsport();      public abstract void setsport(); }  import teams1.*; abstract class footballteam1 extends team1{      public string getsport(){         return "football";     }      public void setsport(){         this.sport="football";     } } 

it doesn't compile because sport private in super class, thought footballteam1 inherit it's own copy of sport because extending team1. appreciated. thanks!

you have answered own question. footballteam1 not have access private fields of parent. 'protected' scope used for.

however, child footballteam1 have own copy of field. has copy of fields parent class has, can see cause confusion.

the reason distinction modularity. subclass of parent class has access parts of parent class 1 has explicitly stated may have access to. allows developers consider parts of class exposed, under object orientated goal known 'open/closed principle'; is, classes should open extension, closed modification.

the quickest 'fix' class change scope of field, example

private string sport = new string(); 

becomes

protected string sport = new string(); 

or

public string sport = new string(); 

if not want give child class direct access field, want allow change field protected setter method used. example, add following team1.

protected void setsport( string newvalue ) {     this.sport = newvalue; } 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -