How to Create Subclasses in Java

Inheritance is related to the idea of specializing an existing class. For example, we may wish to create a class SavingsAccount that has all the characteristics of the Account class, except that a minimum balance has to be present in SavingsAccount.

SavingsAccount

class SavingsAccount extends Account
{
double minBalance;

public SavingsAccount(int no, String name, double balance)
{
super(no, name, balance);
minBalance = 100;
}

public double withdraw(double amount)
{
if (balance - amount < minBalance)
{
System.out.println(''Insufficient Funds");
}
else
{
balance = balance - amount;
}

return balance;
}
}

Rather than completely write from scratch all the code for SavingsAccount, we want to reuse as far as possible variables and methods from the Account class. Additionally, we would like to redefine the withdraw method to ensure that the balance does not fall below the required level. The SavingsAccount class is an example of the specialization of the Account class. The SavingsAccount class can be regarded as a subclass of the parent class, or superclass, Account. In Java, the extends keyword is used to define a subclass.

The SavingsAccount class inherits both state (variables) and behavior (methods) from the parent Account class. So a SavingsAccount object has a corresponding balance
instance variable. SavingsAccount also has an associated deposit method. The withdraw method has been redefined for the SavingsAccount class: this is an example of method overriding. Method overriding is another aspect of polymorphism. We have also created a constructor for SavingsAccount.

Recall that a constructor has the same identifier as the class to which it belongs. In line 5, the super keyword invokes the parent class constructor. If we leave out this statement, Java automatically invokes the parent constructor with an implied super() statement. Since we do not have a constructor in the Account class without arguments, namely, Account(), we have to explicitly enter the super statement so as to invoke Account(int no, String name, double balance).

CreateSavingsAccount illustrates how we might invoke the SavingsAccount class.

CreateSavingsAccount

class CreateSavingsAccount
{

public static void main(String[] args)
{
double balance;

SavingsAccount fredsAccount = new SavingsAccount(123, ''Fred", 60);
fredsAccount.deposit(70);
balance = fredsAccount.withdraw(40);
balance = fredsAccount.withdraw(20);
System.out.println("Balance: " + balance);
System.out.println("A/c No: " + fredsAccount.accountNo);
}
}
Note that the statement in line 8 invokes the deposit method inherited from the Account class. The statement in line 9 invokes the overridden withdraw method defined
in the SavingsAccount class. Since the remaining balance falls below the minimum balance required, this transaction will fail. The second withdraw method invocation in line 10 does not violate the minimum balance requirement and so succeeds. Note that in line 12 we refer to fredsAccount.accountNo. There is no accountNo instance variable explicitly defined in the SavingsAccount class; this variable has been inherited from the Account class. The following output shows the result of executing the
CreateSavingsAccount class:

> java CreateSavingsAccount
Insufficient Funds
Balance: 110.0
A/c No: 123


In CreateBothAccounts, we create an object fredsAccount of type SavingsAccount if the supplied program parameter is equal to 1; otherwise, we create
an object soniasAccount of the parent class type, Account.

CreateBothAccounts

class CreateBothAccounts
{

public static void main(String[] args)
{
Account acc;
double balance;
int arg;
arg=Integer.ParseInt(args[0]);
SavingsAccount fredsAccount =new SavingsAccount(123, ''Fred", 120);
Account soniasAccount = new Account(456, "Sonia", 120);
If(arg == 1)
{
acc=fredsAccount;
}
else
{
acc = soniasAccount;
}
balance = acc.withdraw(30);
}
}


We define an acc object of type Account (line 4). This is set to fredsAccount, a child Savings-Account object, if the program parameter is equal to 1 (line 13). Otherwise, acc is set to soniasAccount, a parent Account object (line 15). The crucial line is 17:if the acc object is soniasAccount, the Account withdraw method is invoked, and the resulting balance is 90. If the acc object is fredsAccount, then the overridden SavingsAccount withdraw method is invoked. Since a SavingsAccount requires a minimum balance of 100, the withdrawal is rejected and the balance remains at 120. This ability of an object variable to refer to a class or its subclass is another aspect of polymorphism. Because the decision as to which withdraw method to invoke is made at runtime, and not compile time, it is known as dynamic binding.

We can create chains of inheritance in Java; a subclass will inherit variables and methods explicitly defined in its immediate parent class. Any variables implicitly inherited by the parent class will be also inherited by the subclass. For example, we may want to specialize the SavingsAccount class still further and create a HighInterestSavingsAccount. This class would inherit variables and methods explicitly defined in the SavingsAccount class, namely, the overridden withdraw method. HighInterestSavingsAccount would also inherit the accountNo, accountName, balance variables, and deposit method from the Account class. Of course, any of these can be overridden, in turn, by the HighInterestSavingsAccount class. Note that Java supports only single inheritance; namely, a class can have at most only one direct parent class.

Note that we can declare a method to be final: this prevents subclasses from overriding the method. For example,

public final double withdraw(double amount)
{


We can also declare a class to be final if we want to prevent further subclassing. For example,

final class SavingsAccount extends Account
{


We have already used the super keyword to call the parent class constructor. Another use of the super keyword is to invoke any method from the parent class. The syntax for this is
super.method_identifier(optional arguments). For example, we can add the deposit method shown next to the SavingsAccount class. This method merely invokes the Account class deposit method, then prints the resulting balance.


deposit Method

public void deposit(double amount)
{
super.deposit(amount);
System.out.println(''New balance: " + balance);
}

No comments:

Post a Comment