Java Inheritance Example

Inheritance in Java is a class can be extends from a partent class and takes the properties and functions from the parents and also be able to override them. The example here demonstrates a parent class Customer and a child class VIPCustomer. Since VIP class extends from Customer, it doesn’t have to redefine some basic prperties such as customer ID, account name, and balance. It only defines the properties unique to VIP customers, discountRate in this case.

The Customer class

public class Customer {
    
    //fields
    private int    customerID;
    private String accountName;
    private double balance;

    //constructor, takes 3 parameters
    public Customer(int id, String name, double bal) {
        customerID  = id;
        accountName = name;
        balance     = bal;
    }

    public void display() {
        System.out.println("Customer ID: " + customerID);
        System.out.println("Account Name: " + accountName);
        System.out.println("Balance: $" + balance);
    }
}

The VIPCustomer class

public class VIPCustomer extends Customer
{
    //fields
    double discountRate;

    //constructor, takes 4 parameters
    public VIPCustomer(int id, String name, double bal, double rate)
    {
        //Calling the parent class's constructor
        super(id, name, bal);
        discountRate = rate;
    }

    public void display()
    {
        //Calling the parent's class's sdisplay method.
       super.display();
       System.out.println("Discount rate is " + discountRate );
    }
}

The TestCustmomers class to test the Inhertiance of the above two classes.

public class TestCustomers
{
   public static void main(String[] args)
   {
       //Creating a customer and a vip customer
        Customer customer = new Customer(1001, "Nancy", 1000.23);
        VIPCustomer vipCustomer = new 
           VIPCustomer(1002, "Jim", 3456.78, 0.15);

        //Calling the display methods to print the info.
        customer.display();
        vipCustomer.display();
   }
}

The output of the TestCustomers class

    Account Name: Nancy
    Balance: $1000.23
    Customer ID: 1002
    Account Name: Jim
    Balance: $3456.78
    Discount rate is 0.15

Search within Codexpedia

Custom Search

Search the entire web

Custom Search