JAVA
Overriding in Java with an simple code
seoca
2019. 1. 4. 09:36
The specialties of Overriding
1. @Override annotation needed.
2. The parameter(s) and return type must be the same as an inherited from its superclass.
3. Super keyword needs to refer to a parent class.
4. Final methods, private methods and Static methods cannot be overridden.
5. a method overriding can only be written in a subclass, not in the same class.
Example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import java.util.*; class Sports{ String getName(){ return "Generic Sports"; } void getNumberOfTeamMembers(){ System.out.println( "Each team has n players in " + getName() ); } } class Soccer extends Sports{ @Override // annotation String getName(){ // The same parameter return "Soccer Class"; // The same return type } @Override void getNumberOfTeamMembers(){ System.out.println("Each team has 11 players in " + getName() ); } } | cs |
Reference
Hackerrank (https://www.hackerrank.com/)
w3schools (www.w3schools.com)