I was trying to work out how to access/use fields/methods of an abstract class in any subclass and I came across this example on the web.
abstract class Instrument {
protected String name;
abstract public void play();
}
abstract class StringedInstrument extends Instrument {
protected int numberOfStrings;
}
with the concrete example subclass given as
public class ElectricGuitar extends StringedInstrument {
public ElectricGuitar() {
super();
this.name = "Guitar";
this.numberOfStrings = 6;
}
public ElectricGuitar(int numberOfStrings) {
super();
this.name = "Guitar";
this.numberOfStrings = numberOfStrings;
}
@Override
public void play() {
System.out.println("An electric " + numberOfStrings + "-string " + name
+ " is rocking!");
}
}
I have 5 questions pertaining to this - sorry for asking more than one question but they are highly related.
- Is the super() call needed or even valid?. There is no constructor given in the abstract super classes
- Can an abstract class even have a constructor given that it can't be instantiated?
- Is the keyword "this" necessary in this example concerning this.name?
- What is the play() overriding here? When an abstract method is specified in the abstract class doesnt that just tell the compiler the method must be specified by any subclass?
- If the Instrument class, StringedInstrument class, and ElectricGuitar class all specified fields called "name" and each had specified constructors (if allowed) how would each name or constructor be accessed in the ElectricGuitar class definition.