Method overriding in Java

Previous
Next

Method Overriding: Defining a method in Child with the same name and signature of its Parent class.

class Parent
{
	void fun()
	{
		System.out.println("Parent's functionality");
	}
}
class Child extends Parent 
{
	void fun() // Method overriding
	{
		System.out.println("Child's functionality");
	}
	public static void main(String[] args) 
	{
		Child obj = new Child();
		obj.fun(); // It is looking for the method in Child class first. If it is not present in Child then it searches in Parent class.
	}
}

Advantage of Method overriding: Overriding is the concept of updating the functionality of Parent object from Child. We override the existing functionality of Parent class Object in Child class when it is not sufficient to Child. It is the part of inheritance concept.

class Galaxy
{
	camera()
	{
		...... 8 megapixel
	}
}
class Note extends Galaxy
{
	camera()
	{
		...... 16 megapixel  
	}
}

Inheritance mechanism includes:

  • Access Parent object functionality
  • Adding new functionality in Child
  • Update(override) Parent object functionality if required
class SamsungGuru
{
	void call()
	{
		System.out.println("Guru - Call");
	}
	void camera()
	{
		System.out.println("Guru - Camera - 2MP");
	}
}
class SamsungGalaxy extends SamsungGuru
{
	void videoCall()
	{
		System.out.println("Galaxy - VideoCall");
	}
	void camera() // override - rewrite - update
	{
		System.out.println("Galaxy - Camera - 8MP");
	}
}
class Inheritance 
{
	public static void main(String[] args) 
	{
		SamsungGalaxy g1 = new SamsungGalaxy();
		g1.call();  // Accessing existing object feature
		g1.videoCall(); // New feature
		g1.camera(); // Updated feature
	}
}
Previous
Next

Add Comment

Courses Enquiry Form