0

Help with anonymous class

The following code compiles correctly and passed the test, but there's no output. How can it pass if output is expected? public class Main { public static void main(String[] args) { Purchase customer = new Purchase(); Purchase specialCustomer = new Purchase(){ //your code goes here int price; public int totalAmount(int price) { return price - (price*20)/100; } }; System.out.println(customer.totalAmount(1000)); System.out.println(specialCustomer.totalAmount(100000)); } } class Purchase { int price; public int totalAmount(int price) { return price - (price*10)/100; } }

19th May 2021, 2:44 PM
James McKee Jr
James McKee Jr - avatar
6 Answers
+ 3
Ok good job 👍
19th May 2021, 3:30 PM
Ipang
+ 2
I don't see the need for <price> member in either the regular or anonym class here. You can try to remove (or comment) their declarations in the code and it may work.
19th May 2021, 2:57 PM
Ipang
+ 2
You're welcome, But that's kinda odd, I removed both `int price;` declarations and code still works okay. Idk why you got that timeout , cause I don't experience that.
19th May 2021, 3:22 PM
Ipang
+ 1
Thanks, I take out variable in anonymous and it works as it should. Taking out the other one cause time out.
19th May 2021, 3:15 PM
James McKee Jr
James McKee Jr - avatar
+ 1
Must have been a network connection thing, after running again it works both ways. Thanks for the help. Took me while to figure out there was an extra "}" in one area of the original code.
19th May 2021, 3:29 PM
James McKee Jr
James McKee Jr - avatar
0
You are a store manager. You are offering a 10% discount on all items in the store. Today, you have had a total of two customers. To the first, you honored the 10% discount on all purchased items. The second customer, however, purchased a lot of items and you want to give him a bigger discount -- 20% -- to show your appreciation. Complete the program by creating two Purchase objects - 1 for the regular customer, and 1 for a special one, and override the totalAmount() method for the special customer on the fly to set the proper 20% discount. ================================================================================================================================== ================================================================================================================================== public class Main { public static void main(String[] args) { Purchase customer = new Purchase(); Purchase specialCustomer = new Purchase(){ //your code goes here int price; public int totalAmount(int price) { return price - (price*20)/100; } }; System.out.println(customer.totalAmount(1000)); System.out.println(specialCustomer.totalAmount(100000)); } } class Purchase { int price; public int totalAmount(int price) { return price - (price*10)/100; } }
17th Nov 2022, 12:02 PM
Guy Martial KEYOU