[HD Pg 313, Sec. 11.4.1 - overriding-methods]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

[HD Pg 313, Sec. 11.4.1 - overriding-methods]

Post by OCAJO1 »

I suggest that you write a similar example to validate the above rules in case of hiding of a static method.

Code: Select all

class Account{
    double balance; double rate;
    Account(double balance, double rate){
        this.balance = balance;
        this.rate = rate;
    }
    double getInterest( InterestCalculator ic, double yrs ){
        try{
            Number n = ic.computeInterest(balance, yrs, rate); //1
            return n.doubleValue();
        }catch(Exception e){
            System.out.println(e);
            //e.printStackTrace();
        }
        return 0.0;
    }
}

class AccountManager{
    public static void main(String[] args){
        
        Account a = new Account(100, 0.2);
        
        InterestCalculator sic = new InterestCalculator();
        double sinterest = a.getInterest(sic, 3);
        System.out.println("Straight Interest: "+sinterest);
        
        InterestCalculator cic = new CompoundInterestCalculator();
        double cinterest = a.getInterest(cic, 3);
        System.out.println("Compound Interest: "+cinterest);
     }
}     
Given the last line of 11.4.1 and the above code segment from the section, if //line 1 were calling static methods (per definition both overridden and overriding), passing different references will not cause it to access the methods referenced by the passed reference. It will always access the overridden method.

So I was wondering is there a way that instead of passing a reference to the getInterest method, pass the class name? Of course, Number n =ic.computeInterest(balance, yrs, rate); has to change to something like Number n =className.computeInterest(balance, yrs, rate);

Thanks

admin
Site Admin
Posts: 10058
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 313, Sec. 11.4.1 - overriding-methods]

Post by admin »

You could create a lambda expression and pass the method reference to the static method that you want to pass. (Not in scope for OCAJP 8).
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: pavvel and 103 guests