An abstract class is a partial blueprint: it can hold shared code, but leaves some methods for subclasses to fill in.
Java · beginner · 8 min · 21 steps · free
abstract class Employee {
String name;
Employee(String name) { this.name = name; }
abstract double pay();
String payslip() {
return name + ": " + pay();
}
}
class Salaried extends Employee {
Salaried(String name) { super(name); }
double pay() { return 3000; }
}
class Hourly extends Employee {
int hours;
Hourly(String name, int hours) { super(name); this.hours = hours; }
double pay() { return hours * 20; }
}
public class AbstractDemo {
public static void main(String[] args) {
Employee a = new Salaried("Asha");
Employee b = new Hourly("Ben", 40);
System.out.println(a.payslip());
System.out.println(b.payslip());
}
}Employee constructor to set up the new object, with name = "Asha".Employee() has finished, so its variables are gone. name in the Salaried object changes from null to "Asha".Salaried() has finished, so its variables are gone.Hourly constructor to set up the new object, with name = "Ben" and hours = 40.Employee constructor to set up the new object, with name = "Ben".Employee() has finished, so its variables are gone. name in the Hourly object changes from null to "Ben".Hourly() has finished, so its variables are gone.b is created on the stack and points to a new Hourly on the heap: {hours: 40, name: "Ben"}.payslip(). It gets its own variables on the stack.payslip() has finished, so its variables are gone.Asha: 3000.0.payslip(). It gets its own variables on the stack.pay() has finished, so its variables are gone.payslip() has finished, so its variables are gone.Ben: 800.0.Answer: Yes. payslip() is a normal method.
Answer: It must be abstract too, or it will not compile. Concrete classes must implement every abstract method.
← Polymorphism and Overriding · Interfaces →