0
Special Discount Customers Anonymous Classes
So in this exercise I am supposed to give a 10% discount to the 1st customer but override the totalAmount() method and give the second customer a 20% discount. Problem is my code won’t compute. It is saying I am missing a “;”. Can someone tell me where to put that and if anything else is wrong with my code. This is what I ahoy so far: https://code.sololearn.com/c2fGd8trcRzW/?ref=app
14 Answers
+ 5
Guy Robbins both of these guys are worth following. It isn't really an and or as Ipang and D_Stark are both well versed.
+ 5
`Main` class should extend `Purchase` class in order to override a method from `Purchase` class.
And <specialCustomer> needs to be an instance of `Main` class in order to use the overridden `totalAmount` method. Because we are overriding `totalAmount` in `Main` class.
https://code.sololearn.com/cGsb9FQSwWAA/?ref=app
+ 5
D_Stark
As I understand it, overriding a method is part of inheritance lesson?
+ 4
Ipang main doesn't need extend anything for anonymous class it's fine doing this in the main method and overriding its methods there, his code is good just the brackets were getting messy. 🙂
+ 4
BroFar sir,
I can firmly confirm that D_Stark get to know Java earlier than me 👌
+ 4
//Please Subscribe to My Youtube Channel
//Channel Name: Fazal Tuts4U
public class Main {
public static void main(String[] args) {
Purchase customer = new Purchase();
Purchase specialCustomer = new Purchase() {
@Override
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;
}
}
+ 3
Thank you D_Stark that exactly what it was. Once i fixed the brackets the code worked perfectly. I really appreciate the help. I am hoping on becoming a software developer really really soon.
+ 3
Ipang yes usually you override methods in extending class but his code is using an anonymous inner class hes overriding on the fly as they call it... theres also a lambda expression for doing this via interfaces .
best way to see this is to print both objects in this code you will notice the refrenece are very diffrent.
+ 3
D_Stark
I understand now
Thank you for new knowledge 🙏
0
For this exercise, where the code should be, the page is blank. Is it a bug, or am I supposed to write everything from line 1 myself ?
0
public class Main
{
public static void main(String[] args) {
Purchase customer = new Purchase();
Purchase specialCustomer = new Purchase(){
//your code goes here
@Override 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;
}
}