Understanding Abstract Classes... am I getting this?
New JAVA programmer here, and I have looked online at multiple tutorials about abstract classes and managed to get them to work successfully... just not sure I have this quite right.
I will use my current implementation as an example.
This is my abstract class:
Code Java:
public abstract class charGen {
private String namez;
private int HP;
private int STR;
private float AGI;
public charGen(String name, int hp, int str, float agi){
this.namez = name;
this.HP = hp;
this.STR = str;
this.AGI = agi;
}
public String getName(){
return this.namez;
}
public int getHP(){
return this.HP;
}
public int getSTR(){
return this.STR;
}
public float getAGI(){
return this.AGI;
}
public void setName(String n){
this.namez = n;
}
public void setHP(int h){
this.HP = h;
}
public void setSTR(int s){
this.STR = s;
}
public void setAGI(float a){
this.AGI = a;
}
public abstract String specialSTR();
public abstract String getRace();
public abstract void resetHP();
}
This is one of my classes that extends charGen:
Code Java:
public class charOrc extends charGen{
public charOrc(String n, int h, int s, float a) {
super(n,h,s,a);
}
public String specialSTR(){
return super.getName() + " erupts into a vicious Orc frenzy!";
}
public String getRace(){
return "Black Orc";
}
public void resetHP(){
super.setHP(150);
}
}
Just curious if this is the proper way to use an abstract class? I find it handy since it handles all the simple methods that my different sub-classes have in common, but will relegate the particulars back to those classes to handle.
Did that make sense? :confused:
Re: Understanding Abstract Classes... am I getting this?
Yes, the usage is correct. One side note, you do not need to prefix the calls with "super" when you call getName() and setHP() as there is only one instance of these methods. It would make more sense to prefix a call with super if you had overridden the method and you want to call the parent method.
As an example. Say the parent class defines a toString() method and you implement a subclass. The subclass wants to implement the toString() method and add any new fields it may have defined to it so you may do something like the following:
Code :
parents toString
public String toString() { return "Parent"; }
child toString
public String toString() {
return super.toString() + " Child";
}