Understanding OOP Concepts: Method Overriding
In this article, we’re going to learn the method overriding concept in OOP. Let’s get started:
Table of Contents
What is Method Overloading?
Method Overloading is a technique that allows a subclass to declare the same method which is already present in the parent class. This technique is an example of runtime polymorphism or dynamic method dispatch.
An example:
class Animal {
public void displayInfo() {
System.out.println("I am an animal");
}
}
class Cat extends Animal {
@override
public void displayInfo() {
System.out.println("I am a cat.");
}
}
class Main {
public static void main(String[] args) {
Cat c1 = new Cat();
c1.displayInfo();
}
}
Rules of Overloading
There are some rules of method overriding. I’m going to mention some of the rules in short.
Rules 1: The parent class and the child class must have the same method name.
Rules 2: The parent class and the child class must have the same parameter & return type.
Rules 3: The static
& final
methods cannot be overridden. In Java, private
methods cannot be overridden too.
Rules 4: Abstract method must be overridden in child class.
Rules 5: Constructor cannot be the same for a parent class and a subclass.
The Super Keyword
By using the super
keyword, we can access the parent class methods from the child class.
Let’s see an example:
class Animal {
public void displayInfo() {
System.out.println("I am an animal");
}
}
class Cat extends Animal {
public void displayInfo() {
super.displayInfo();
System.out.println("I am a cat");
}
}
class Main {
public static void main(String[] args) {
Cat c1 = new Cat();
c1.displayInfo();
}
}
The output:
I am an animal
I am a cat
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)