java - Constructor (super-, sub-, subsubclass) - Help and tips :) -


i'm working on project , made example easly explains problem.

i've made superclass (abstract), subclass (abstract) , subsubclass. there piece of code want try keep in constructor of superclass, won't work correctly until put subclass instead.

the superclass:

public abstract class superclass{  protected int x, y, halfx, halfy;  public superclass(){     halfx = x / 2;     halfy = y / 2; } 

the subclass:

public abstract class subclass extends superclass{  public subclass(int x, int y){     this.x = x;     this.y = y; } 

the subsubclass:

public class subsubclass extends subclass{  int half;  public subsubclass(int x, int y){     super(x, y); }  public void mymethod(){     half = halfx + halfy; } 

if remove halfx = x / 2; halfy = y / 2; superclass constructor , put subclass constructor, code works perfectly. this:

public abstract class subclass() extends superclass{  public subclass(int x, int y){     this.x = x;     this.y = y;      halfx = x / 2;     halfy = y / 2; } 

}

what want have piece of code available other subclasses (and subsubclasses) instead of specify code in subclass.

how should proceed solve this?

thank time :)

just called super(x, y); in subsubclass, need same thing in subclass. there no magic it, pass values superclass x , y set before attempt calculate half value.

i highly recommend making fields final ever possible , in case should final.

btw: if want see happening can step through code in debugger.

public abstract class superclass{      protected final int x, y, halfx, halfy;      public superclass(int x, int y){         this.x = x; // set x before using it.         this.y = y; // set y before using it.         halfx = x / 2;         halfy = y / 2;     } }  public abstract class subclass extends superclass{      private final int z;      public subclass(int x, int y, int z){         super(x, y);         // set fields of subclass         this.z = z;     } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -