For Video Tutorial : Move on Youtube Channel
Note : Select the playlist as per your need & move with number sequence
Method overriding in java with example
For Video : CLICK HERE
As we know that in Inheritance(extends keywords) child class will inheritate all non-private member of Parent class. But if parent class & child both have same method then ??
Then there is a chance to override the method provided that it is not marked final.
So we have to create a reference object for both Child and parent class to access these simillar methods .
Object Creation : Parent_Class object_name = new Parent_class(); //to access parent method
Parent_class object_name = new Child_class(); //to access child method
This oops feature is known as "Method overriding"
Example : In below example child class have simillar method as parent class & child class is inheriting parent class, so methods of clid and parent can be accessed by appropriate object reference.
package chandan_test1;
class Parent
{
public void sum(int a, int b)
{
System.out.println("the sum is :" + (a+b));
}
}
class child extends Parent
{
public void sum(int a, int b)
{
System.out.println("the difference is:" +(a-b));
}
}
public class chandan_override
{
public static void main(String args[])
{
Parent obj = new Parent();
Parent ob = new child(); //parent reference but child object.
obj.sum( 5,7);
ob.sum(10, 20);
}
}
Output:
the sum is :12
the difference is:-10
No comments:
Post a Comment