How to Override Java Inheritance

Like other object-oriented programming languages, Java implements the concept of inheritance. A class can be declared to be a subclass of another class (commonly called the "parent class"). The subclass inherits all methods from the parent class. If the subclass redefines an inherited method with the same signature, the definition in the subclass overrides that in the superclass. You can override Java's built-in inheritance mechanism in your code.

Instructions

    • 1

      Define the parent class in your Java application, as in the following sample code:

      public class BankAccount {

      private float balance;

      public BankAccount(float initialBalance) {

      balance = initialBalance;

      }

      public withdraw(float amount) {

      balance -= amount;

      }

      }

    • 2

      Define the subclass using Java's keyword "extends", as in the following sample code:

      public class SavingsAccount extends BankAccount {

      }

      By default, SavingsAccount (a particular case of BankAccount) will inherit the attribute "balance" and the two methods from its parent class.

    • 3

      Override a method by declaring it within the subclass with exactly the same signature as in the parent class, as in the following sample code:

      public class SavingsAccount extends BankAccount {

      private int transactionsThisMonth = 0;

      public withdraw(float amount) {

      if (transactionsThisMonth < 6) {

      balance -= amount;

      transactionsThisMonth++;

      }

      }

      }

      The new version of method "SavingsAccount.withdraw()" overrides the inherited method "BankAccount.withdraw()"; in this example, the reason is that savings accounts are subject to monthly limits in the number of allowable transactions. The constructor and the "balance" attribute are still unchanged, as inherited from the parent class.

Related Searches:

References

Comments

Related Ads

Featured