Changing property type of a class in JAVA OOP - Implicit and Explicit casting

Viewed 46

I have been studying explicit and implicit casting in Java.
I created a Customer class that has two subclasses like RetailCustomer and CorporateCustomer. Also, I created a Bill class that has Customer property.

I want to create a Bill object according to user selection. If the user selects "1", the Bill object will be created for the retail customer, or if the user selects "2", the Bill object will be created for the corporate customer.

I'm very confused. How can I use explicit and implicit casting?

public class Customer {
    
    private int CustomerID;
    private String CustomerName;
    private String CustomerLastName;
}
    
public class RetailCostumer extends Customer {
    
    private int CitizenShipID;
    private int CustomerNo
}
    
public class CorporateCustomer extends Customer {
    
    private int TaxNumber;
    private int CustomerNo
}
    
    
public class Bill {
    
    private int BillID;
    private Customer customer;
}
    
public class BillManagement {

    public static void main(String[] args) {

    }
}
1 Answers

You don't have to explicit casting when creating and assigning subclass to superclass.

For example:

// You can assign RetailCustomer(subclass) instance to a Customer(superclass), 
// Because RetailCustomer is Customer.
Customer customer = new RetailCustomer();

But, when you want to access subclasses variable such as CitizenShipID, TaxNumber, then you need to use explicit type casting.

For example:

Customer customer = new RetailCustomer();

// Customer could not be RetailCustomer (e,g. could be CorporateCustomer) , 
// so, you have to inform that 'customer is actually RetailCustomer'
RetailCustomer retailCustomer = (RetailCustomer) customer;

retailCustomer.CitizenShipID;

In practice, actual customer instance could not be a RetailCustomer instance(could be CorporateCustomer), then ClassCastingException will be occurred.

So, it will be good practice to check actual instance type by instanceof before casting like below.

Customer customer = new RetailCustomer();

RetailCustomer retailCustomer;

if (customer instanceof RetailCustomer) {
  retailCustomer = (RetailCustomer) customer;
} else {
 // handle otherwise
}

retailCustomer.CitizenShipID;
Related