0

How does the @Override method work in Java?

I'm trying to learn the @Override method and how inheriting works in Java. I believe I've gathered how child and parent classes work.

Below I have one driver class, one parent class and then two child classes.

What I'm trying to do is have the toString method in the SimpleBankAccount class called. However, the toString methods in the child classes are getting called.

public class AccountsDriver{
    final public static double INTEREST_RATE = 0.01;  // 1%

    public static void main( String[] args ){
        CheckingAccount checking = new CheckingAccount( 100.0 );
        SavingAccount savings = new SavingAccount( 1000.0, INTEREST_RATE );

        double monthlyExpenses = 756.34;
        int electricBillCheckNum = 2123;
        double electricBill = 60.34;
        int registationCheckNum = 2124;
        double registration = 50.00;
        double dinnerMoney = 55.32;
        double futureCar = 200.0;
        double textbook = 90.0;
        checking.deposit( monthlyExpenses );
        checking.processCheck( electricBillCheckNum, electricBill );
        checking.withdraw( dinnerMoney );
        checking.processCheck( registationCheckNum, registration );
        System.out.print( checking.toString() );
        savings.deposit( futureCar );
        savings.applyInterest( );
        savings.withdraw( textbook );
        System.out.print( savings.toString() );
    }
}
public class SimpleBankAccount
{
    protected double balance;
    public boolean withdraw(double amount){
        if (balance - amount >= 0){
            balance -= amount;
            return true;
        }else{
            return false;
        }
    }
    public String toString(){
        //display balance as currency
        String balanceStr = NumberFormat.getCurrencyInstance().format(balance);
        return "Balance: " +balanceStr+ "\n";
    }
}
public class CheckingAccount extends SimpleBankAccount
{
    int lastCheck;
    public CheckingAccount(double amount){
        balance = amount;
    }
    public boolean processCheck(int checkNum, double amount){
        if (lastCheck == checkNum){
            return false;
        }else{
            balance -= amount;
            lastCheck = checkNum;
            return true;
        }
    }
    public String toString(){
        //display the balance as currency
        String balanceStr = NumberFormat.getCurrencyInstance().format(balance);
        return "Checking Account: \n Balance: " +balanceStr+ "\n Last processed check: " +lastCheck;
    }
}
public class SavingAccount extends SimpleBankAccount
{
    double interestRate;
    public SavingAccount(double amount, double interestRate){
        balance = amount;
        this.interestRate = interestRate;
    }
    public void applyInterest(){
        balance = (balance*interestRate)+balance;
    }
    public String toString(){
        //display balance as currency
        String balanceStr = NumberFormat.getCurrencyInstance().format(balance);
        return "Saving Account: \n Balance: " +balanceStr+ "\n APR: " +interestRate;
    }
}

Can someone point out what I'm doing wrong?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • "the toString methods in the child classes are getting called" - that is exactly how inheritance is supposed to work. You override the superclass method with a subclass method to define the behaviour of objects of the subclass. – sprinter Mar 05 '20 at 04:02
  • Related: [When do you use Java's @Override annotation and why?](https://stackoverflow.com/q/94361/6395627). – Slaw Mar 05 '20 at 05:59

3 Answers3

1

In your code, you are not using the @Override annotation (this is optional), although you are still overriding the method. From Predefined Annotation Types:

@Override annotation informs the compiler that the element is meant to override an element declared in a superclass.

Also:

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

As per sprinter in the comments, the child methods gets called, unless you do a super.methodName() to have the parent method called.

geffchang
  • 3,279
  • 2
  • 32
  • 58
0

Overriding a method basically does what it says ... overrides what would've traveled up to the parent and been called ... the parent doesn't get called anymore, now your overridden method in the child is what gets called.

If you also wanted to include what the parent 'said' in its toString() method after you've overridden it, you would force a call to the parent inside of your overridden child toString() method with a specific call to:

super.toString();

That is saying ... call the parents version of this method.

...
@Override
public String toString() {
  return super.toString() + (concatenate your additional child info onto the super info.)
}

super.(method) ... calls the parent method you've overridden.

It's like how this.toString() calls the toString() method in THIS class ... super.toString() calls the method in the SUPER class (the parent.)

We don't usually need to use 'this.', 'this.' ... is implied. We do need to explicitly state 'super.' (if that's what we want called instead of, or along with, 'this.')

I'll add that sometimes you want to start other types of overridden methods with a call to execute the super. version of the method from inside of the overridden method in the child. Then, it does all that work the super is doing, and you are just adding a bit of extra functionality that the child class will now add to that basic super methods work. Often, you still wanted that to run too ... so you call it from inside the method you've overridden with a call to also execute the super.yourOverriddenMethod(); ... usually first.

Lotsa
  • 412
  • 4
  • 11
0

Firsly @Override is not a method it is called an annotation

Now

Suppose that you extend a class but your're not happy with some method in your parent class in your class you want them to do something else. Then you override that method in your class.

For example - your super class has a method like below

public void print(){
System.out.println("Hi");
}

But when you call this method you want it to print "Hello" then in subclass you do something like below

public void print(){
System.out.prinlnt("Hello");
}

The compiler detects that you have a method with same signature as your parent class does, it means you want to override your parent class method and run your own implementation.

Even if you don't use annotation @Override you still overriding that method

so question is what is use of @Override?

It basically serves 3 purpose

  1. Suppose you are overriding without @Override and by mistake you are defining print() as printt() by mistake , you think you are overriding print but because of that typo , the printt() is now a separate method , now you're calling print() think that your print() will be called but you don't have a print() method to parent print() will be called, this is not an error and you will be thinking why your print() is not called.

so using @Override prevents you from doing any typo in method name. now if you do

@Override
public void printt() // that is actually an error, without @Override it's not
  1. The second is, for example you don't know your super class have a print(int i) which prints the square of i method and you're defining a method print() method in your class, now you or your user by mistake calls print(int i) then parent version is called and you will be thinking i never defined a function which prints the square of a number , then where does it coming from.

@Override will also prevent you from doing any changes in method signature you want to override as well as it means you know that there is a method print() in your parent which you want to override.

  1. The third is readability , if someone else read your class definition he can see that the method annotated with @Override are also in parent and this is an Overriden version.

Thanks

Abhinav Chauhan
  • 1,304
  • 1
  • 7
  • 24