Constructors, fields and normal methods in abstract classes
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)An abstract class is still a full class. Besides abstract methods, it can have fields, constructors and concrete methods. Only one thing is blocked: new on the class itself.
An abstract class is still a full class
Sleeper and AC tickets both have a passenger name, a base fare and the same check on the fare. The abstract parent Ticket can hold all of that, so no child repeats it.
abstract class Ticket { protected String passenger; protected int baseFare;
Ticket(String passenger, int baseFare) { if (baseFare < 0) { baseFare = 0; } this.passenger = passenger; this.baseFare = baseFare; }
abstract int extraCharge();}The fields and the check are what is the same for every ticket. The abstract method holds what is different: extraCharge(). Each child writes only that one method, and a change to the fare check is made in one place.
Its constructor runs through super()
You never write new Ticket(...), yet Ticket has a constructor. It runs when a child object is created: the child's constructor calls it with super(...) as its first line, as in The super keyword (opens in a new tab).
Example 1 · The abstract parent constructor runs first
abstract class Account { protected String holder; protected int balance;
Account(String holder, int balance) { this.holder = holder; this.balance = balance; System.out.println("Account constructor: " + holder); }
void deposit(int amount) { balance = balance + amount; }
abstract int interestRate();}
class Savings extends Account { Savings(String holder, int balance) { super(holder, balance); System.out.println("Savings constructor"); }
@Override int interestRate() { return 4; }}
public class AccountDemo { public static void main(String[] args) { Account a = new Savings("Priya", 10000); a.deposit(2000); System.out.println("Balance: Rs. " + a.balance); System.out.println("Yearly interest: Rs. " + a.balance * a.interestRate() / 100); }}Account constructor: Priya Savings constructor Balance: Rs. 12000 Yearly interest: Rs. 480
What this code does
new Savings(...)callssuper(holder, balance), so the abstractAccountconstructor runs first and sets the shared fields.depositis a concrete method written once in the parent;interestRateis the only partSavingsmust write.
Example 2 · Shared fields and one check, written once
abstract class Ticket { protected String passenger; protected int baseFare;
Ticket(String passenger, int baseFare) { if (baseFare < 0) { baseFare = 0; } this.passenger = passenger; this.baseFare = baseFare; }
abstract int extraCharge();}
class SleeperTicket extends Ticket { SleeperTicket(String passenger, int baseFare) { super(passenger, baseFare); }
@Override int extraCharge() { return 0; }}
class AcTicket extends Ticket { AcTicket(String passenger, int baseFare) { super(passenger, baseFare); }
@Override int extraCharge() { return 900; }}
public class TicketDemo { public static void main(String[] args) { Ticket[] tickets = { new SleeperTicket("Arjun", 450), new AcTicket("Diya", -100) }; for (Ticket t : tickets) { System.out.println(t.passenger + ": Rs. " + (t.baseFare + t.extraCharge())); } }}Arjun: Rs. 450 Diya: Rs. 900
What this code does
- The negative-fare check lives only in the parent constructor, so every ticket type gets it for free.
- The children have no fields of their own; their constructors just pass the values up with
super(...).
Example 3 · Mistake: the child forgets super(...)
abstract class Ticket { protected String passenger;
Ticket(String passenger) { this.passenger = passenger; }
abstract int fare();}
class TatkalTicket extends Ticket { TatkalTicket(String passenger) { System.out.println("Tatkal for " + passenger); }
@Override int fare() { return 1200; }}
public class SuperMissingDemo { public static void main(String[] args) { Ticket t = new TatkalTicket("Aarav"); System.out.println(t.fare()); }}SuperMissingDemo.java:12: error: constructor Ticket in class Ticket cannot be applied to given types;
TatkalTicket(String passenger) {
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 errorWhat this code does
- With no
super(...)line, Java tries to callTicket()with no arguments.Tickethas onlyTicket(String), so it fails. - Fix: make
super(passenger);the first line of theTatkalTicketconstructor.
The order is the one from Constructor order (opens in a new tab): parent constructor first, then the child's. If the parent has only a constructor with parameters, every child must call super(...) with values.
Order of execution
Which constructor runs first?
Tap the steps in the order they happen.
protected, because only children call it. public also works, since new is blocked anyway.Template method: fixed steps, one blank
A template method is a concrete method in a parent class that fixes the steps and their order, and calls abstract methods for the steps that differ. Each child fills in only those steps. It is usually marked final.
Every food order prints the customer, the food total, the delivery charge and the amount to pay, always in that order. Only the delivery rule differs. So placeOrder() is written once and calls deliveryCharge() in the middle.
Example 4 · Template method: a final method calls an abstract step
abstract class FoodOrder { protected String customer; protected int foodTotal;
FoodOrder(String customer, int foodTotal) { this.customer = customer; this.foodTotal = foodTotal; }
final void placeOrder() { int delivery = deliveryCharge(); System.out.println("Customer: " + customer); System.out.println("Food Rs. " + foodTotal + " + delivery Rs. " + delivery); System.out.println("Pay: Rs. " + (foodTotal + delivery)); }
abstract int deliveryCharge();}
class NormalOrder extends FoodOrder { NormalOrder(String customer, int foodTotal) { super(customer, foodTotal); }
@Override int deliveryCharge() { if (foodTotal >= 300) { return 0; } return 40; }}
class ExpressOrder extends FoodOrder { ExpressOrder(String customer, int foodTotal) { super(customer, foodTotal); }
@Override int deliveryCharge() { return 80; }}
public class OrderDemo { public static void main(String[] args) { new NormalOrder("Kavya", 350).placeOrder(); new ExpressOrder("Rohan", 200).placeOrder(); }}Customer: Kavya Food Rs. 350 + delivery Rs. 0 Pay: Rs. 350 Customer: Rohan Food Rs. 200 + delivery Rs. 80 Pay: Rs. 280
What this code does
placeOrderis written once and fixes the steps. In the middle it callsdeliveryCharge(), and each object runs its own version.placeOrderisfinal, so no child can change the order of the steps; they can only fill in the delivery rule.
Example 5 · Mistake: a child overrides the final template method
abstract class FoodOrder { final void placeOrder() { System.out.println("Delivery: Rs. " + deliveryCharge()); }
abstract int deliveryCharge();}
class ExpressOrder extends FoodOrder { @Override int deliveryCharge() { return 80; }
@Override void placeOrder() { System.out.println("Free delivery!"); }}
public class FinalTemplateDemo { public static void main(String[] args) { new ExpressOrder().placeOrder(); }}FinalTemplateDemo.java:14: error: placeOrder() in ExpressOrder cannot override placeOrder() in FoodOrder
void placeOrder() {
^
overridden method is final
1 errorWhat this code does
placeOrderisfinalin the parent, so a child may not replace it. This protects the fixed steps.- The child may only change what the parent left open: the abstract
deliveryCharge.
Which deliveryCharge() runs? The one of the actual object, as in Dynamic method dispatch (opens in a new tab). Marking placeOrder() final (see final methods and classes (opens in a new tab)) stops a child from changing the order or skipping a step.
What goes where
A simple way to decide where each piece of code belongs in an abstract class family:
- Same for every child (fields, checks, printing) → a field or concrete method in the abstract parent.
- Different for every child → an
abstractmethod that each child implements. - The order of steps must never change → a
finaltemplate method that calls the abstract steps. - Setting shared fields → the parent constructor, called with
super(...)from each child.
0 or null.Next step
Check your understanding
11 quick questions