Why to use @override method, while overriding the method in child class. The code is working fine without @override keyword too

class BankAccount//parent class

{

protected double balance;

BankAccount(int bal)

{
    balance = bal;
}
public void printBalance()
{
    System.out.println("Your account balance is $"+balance);
}

}

class CheckingAccount extends BankAccount //child class
{
int balance;

  public  CheckingAccount(int bal)
    {
        super(bal);
        balance = bal;
    }

//no @override keyword

public void printBalance() //method overriding

{
    System.out.println("Your checking balance is $"+balance);
}
public void checkBalance()
{
    super.printBalance();
    printBalance();
}
public static void main(String [] args)
{
    CheckingAccount check = new CheckingAccount(5000);
check.checkBalance();

}
}

Welcome to the forums!

Using @Override can help in situations where you misspelled the name of a method or if you’ve changed the name or parameters of the method that is being overridden. This is because you’re telling the compiler explicitly that this method is overriding another method. You’ll get a compile-time error in this case and avoid unexpected outputs.

Side note: in future posts, please format your code using the </> button.

1 Like