ISCL is a Intelligent Information Consulting System. Based on our knowledgebase, using AI tools such as CHATGPT, Customers could customize the information according to their needs, So as to achieve

How to Override Java Inheritance

2
    • 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.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.