0

Method Overriding in Java

Can I override the method within the class in Java? If so, please give an example! Thanks for the response.

26th Apr 2024, 12:05 PM
Shizuka
Shizuka - avatar
2 Answers
+ 2
Let's try to help you. I create a product class. This class represents a generic product. This class representing any item in a store. It calculates the total price with a 5% tax. Another class name ElectronicProduct. This class is a special type of product with an additional 10% tax. It extends the Product class and overrides the calculateTotalPrice() method to include this additional tax. That might be a good example. Or, in the main class we create instances of both Product and ElectronicProduct and print their details, including their names, prices, and total prices after tax calculations. Here, an ElectronicProduct can have its own way of calculating the total price compared to a generic Product. Now, take a look at the code: https://sololearn.com/compiler-playground/ce6qyQKqmutq/?ref=app
26th Apr 2024, 1:38 PM
`ᴴᵗᵗየ
`ᴴᵗᵗየ - avatar
+ 1
The method in the class? There’s not just one method or class. If you are talking about class A having method D, and class B being derived from class A but having its own definition for method D, then yes the class B method D will override its inherited method D. Class A will still have the original method D though.
26th Apr 2024, 1:10 PM
Wilbur Jaywright
Wilbur Jaywright - avatar