Monday, December 10, 2018

Java OOPS: Inheritance (Overriding) Part 1

Hi All,

In previous post we have checked that, in inheritance which method will be called by which reference. Now in this post , we will check that how different cases of overriding takes place in Inheritance.

Case I : 

Let's take a look on this overriding case :

public class InheritanceDemo1 {

public static void main(String [] args){
Parent parent = new Parent();
parent.m1();

Child child = new Child();
child.m1();

Parent parent1 = new Child();
parent1.m1();

}
}
class Parent {
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m1(){
System.out.println("This is child class m1 method");
}
}

Output:

This is parent class m1 method
This is child class m1 method
This is child class m1 method

Explanation: 

This is the simple overriding program. In this the main part to be noticed is Parent parent1 = new Child(); , in this reference of Parent type pointing to the Child class object .So in this class , Child class m1() will be called.

Case II : 

public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Parent();
child.m1();
}
}
class Parent {
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m1(){
System.out.println("This is child class m1 method");
}
}

Output:

error: incompatible types: Parent cannot be converted to Child

Explanation: 

Child child = new Parent(); , in this reference of Child type pointing to the Parent class object . So as we previously noticed that Child class can not be point to Parent class object. 



No comments:

Post a Comment