Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Overriding Methods
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Overriding is an important concept when dealing with inheritance. A subclass' method overrides a superclass' method when it has the same signature, meaning it has the same name and the same parameters. See an example of how you can override a superclass' method below.
OverrideMethodTestOne.java
package exlcode;
public class OverrideMethodTestOne {
public String exampleVariableOne = "Java";
public void print() {
System.out.println(exampleVariableOne);
}
}
OverrideMethodTestTwo.java
package exlcode;
public class OverrideMethodTestTwo extends OverrideMethodTestOne {
public String exampleVariableTwo = "World";
// overrides the print method from OverrideMethodTestOne
public void print() {
// calls the print method from the OverrideMethodTestOne
super.print();
System.out.println(exampleVariableTwo);
}
}
OverridingMethodsExample.java
package exlcode;
public class OverridingMethodsExample {
public static void main(String[] args) {
OverrideMethodTestOne objectOne = new OverrideMethodTestTwo();
objectOne.print();
}
}
The method print() exists in the subclass and superclass with the same signature, and is overridden by the subclass as shown above. The reason why the subclass OverrideMethodTwo overrides the method print() is because it wants to print the extra String "World" on the console. When the statements OverrideMethodTestOne objectOne = new OverrideMethodTestTwo(); and objectOne.print() are called, the program first searches for the print() method in the class OverrideMethodTestTwo before it looks for the print() method in the superclass, which is why the print() method in the subclass is used. If the print() method was not overridden in the subclass, only "Java" would end up being printed to the console.
public classFood{
public void print(){
System.out.print("Food");
}
}
public classBreadextendsFood
{
public void print()
{
System.out.print("Bread");
}
}
What is printed as a result of executing the following code segment?