Skip to lesson

extends: parent and child classes

class Child extends Parent makes Child a child class of Parent. The child gets the parent's fields and methods, and its own body holds only what is new.

How to write extends

extends is the keyword used in a class declaration to make the new class a child (subclass) of an existing class, as in class SmartPhone extends Phone. A class can extend only one class.

A shop app has a Phone class and now needs a smartphone that can also browse. Write class SmartPhone extends Phone and put only the new method inside: extends gives the child everything else.

Example 1 · A child class uses parent and own methods

PhoneDemo.javaJava
class Phone {    String brand;
    void call(String person) {        System.out.println(brand + " calling " + person);    }}
class SmartPhone extends Phone {    void browse(String site) {        System.out.println(brand + " opening " + site);    }}
public class PhoneDemo {    public static void main(String[] args) {        SmartPhone sp = new SmartPhone();        sp.brand = "Samsung";        sp.call("Amma");        sp.browse("irctc.co.in");    }}
Output
Samsung calling Amma
Samsung opening irctc.co.in

What this code does

  • SmartPhone has no brand field of its own; it gets brand and call() from Phone.
  • browse() is the new part. It uses the inherited brand by its plain name.

A child object uses the parent's members as if they were its own, so sp.call() and sp.browse() both work. Inside the child's methods, the parent's fields are used by their plain names, like brand.

A class with no extends still has a parent: Java's built-in class Object. So every class belongs to one big family; The Object class (opens in a new tab) shows what it gives you.

What the child can use

An Employee parent has fields with all four access levels. A child uses a parent member by name only when its access level allows it: the same words as in Access modifiers (opens in a new tab).

Java
class Employee {    public String name;    protected int salary;    int empId;    private String password;}
class Manager extends Employee {    void show() {        System.out.println(name + " " + salary + " " + empId);        System.out.println(password);   // error: password has private access in Employee    }}

Here is what each level allows a child class:

  • public: usable by the child, and by every other class too.
  • protected: usable by the child, even in another package, and by every class in the same package.
  • Default (no word): usable by the child only if it is in the same package.
  • private: never usable by name outside its own class, not even by the child.

Private fields: inside the object, but locked

SavingsAccount wants to add interest to the private int balance of its parent Account. Writing balance in the child is a compile error: private members are not inherited by name.

The variable s on the stack refers to one SavingsAccount object on the heap. Inside it, the part from Account holds private int balance = 5200 and the methods deposit() and getBalance(); the part from SavingsAccount holds addInterest(). Child code reaches balance only through the parent's methods.

Example 2 · Mistake: the child touches a private field

PrivateDemo.javaJava
class Account {    private int balance;
    public void deposit(int amount) {        balance = balance + amount;    }}
class SavingsAccount extends Account {    void addInterest() {        balance = balance + balance * 4 / 100;    }}
public class PrivateDemo {    public static void main(String[] args) {        SavingsAccount s = new SavingsAccount();        s.deposit(5000);        s.addInterest();    }}
Sample compiler output
PrivateDemo.java:11: error: balance has private access in Account
        balance = balance + balance * 4 / 100;
        ^
PrivateDemo.java:11: error: balance has private access in Account
        balance = balance + balance * 4 / 100;
                  ^
PrivateDemo.java:11: error: balance has private access in Account
        balance = balance + balance * 4 / 100;
                            ^
3 errors

What this code does

  • balance is private in Account, so only Account's own code may use it by name.
  • Being a child does not open a private field. The fix is to go through the parent's public methods.

Example 3 · The fix: use the parent's getter and methods

GetterDemo.javaJava
class Account {    private int balance;
    public int getBalance() {        return balance;    }
    public void deposit(int amount) {        if (amount <= 0) {            System.out.println("Invalid amount: " + amount);            return;        }        balance = balance + amount;    }}
class SavingsAccount extends Account {    void addInterest() {        deposit(getBalance() * 4 / 100);    }}
public class GetterDemo {    public static void main(String[] args) {        SavingsAccount s = new SavingsAccount();        s.deposit(5000);        s.addInterest();        s.deposit(-50);        System.out.println("Balance: Rs. " + s.getBalance());    }}
Output
Invalid amount: -50
Balance: Rs. 5200

What this code does

  • The child reads the balance with getBalance() and adds interest with deposit(): 4% of 5000 is 200.
  • The private field lives inside the SavingsAccount object, and the parent's check still blocks -50.

The child object still contains the field: every SavingsAccount has a balance, but only Account's own code can touch it. So the child works through the parent's public methods, like getBalance() and deposit(), as in Getters and setters (opens in a new tab). The parent's checks, such as "no negative deposits", keep protecting the data.

protected: a door for children

protected is an access modifier that lets a member be used by every class in the same package and by child classes in any package.

A Manager needs to raise the salary it gets from Employee. A protected field is open to child classes in any package, and to every class in the same package.

Example 4 · protected lets a child use a field directly

ProtectedDemo.javaJava
class Employee {    protected String name;    protected int salary;}
class Manager extends Employee {    void giveBonus(int percent) {        salary = salary + salary * percent / 100;        System.out.println(name + " now earns Rs. " + salary);    }}
public class ProtectedDemo {    public static void main(String[] args) {        Manager m = new Manager();        m.name = "Priya";        m.salary = 60000;        m.giveBonus(10);        System.out.println(m.salary);    }}
Output
Priya now earns Rs. 66000
66000

What this code does

  • salary is protected, so the child Manager may read and change it directly.
  • main can use it too, because every class in this file is in the same package. That is why protected is weaker than private.

In a single file, all classes share one package, so protected works like default access there. Use it only when children really need direct access. When unsure, keep the field private with a getter: then every change goes through your checks.

Fix the error

Fix the extends error

Read the error, then pick the line that fixes it.

Round 1 of 3

This should make Car a child of Vehicle.

class Vehicle {
String regNo;
}
class Car extend Vehicle {
int seats;
}

Error

Car.java:4: error: '{' expected

Next step

Check your understanding

11 quick questions