Method Overriding in Java or program to demonstrate Method overriding concept. rcubjava

 

Method Overriding in Java


A method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its Superclass is called as Method overriding.

Method overriding is used for runtime polymorphism


Rules for Java Method Overriding

1.The method must have the same name as in the parent class.
2.The method must have the same parameter as in the parent class.
3.There must be an IS-A relationship
(inheritance).
4.The final, static, private methods Cannot be overriden.
5.constrcutor methods are cannot be overriden.
6.We should always override abstract methods of the superclass.
7.The method must have the same return type as in the parent class.


Example: program to demonstrate use of method overriding.

class A
{    
public void display()
{
System.out.println("parent class method");
}
}
class B extends A
{
public void display()
{
System.out.println("child class method");
}
public static void main(String args[ ])
{ B o=new B();
o.display();
}


Output:
child class method

Comments

Popular posts from this blog

Control Statements:Selection statement ,Iteration statement and Jump statement in Java

Abstract classes and Abstract methods in Java with Examples rcub.

Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.