Tuesday, December 11, 2018

Java OOPS: Inheritance (Overriding) Part 4 Abstract Methods

Hi All ,

In previous post we checked how final or private methods worked in Inheritance concept .Now in this post we will check how abstract method will work between Parent and Child class.

Case I :  

In first case we will check how abstract method is used in child class .Let's take a look:

public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}
abstract class Parent {
abstract void m1();
}

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

Output :

This is child class m1 method

Explanation:  

In this example we can see that the abstract method of Parent class must be defined in Child Class method. If it is not defined here , then Child class must also be declared as abstract class and then in this class this Child class must be extend by any other class.


Case II :  

If we are trying to make the Child class as an abstract class with a abstract method .This abstract method will have same name as the Parent Class method , then it will also valid .Let's take a look:

public class InheritanceDemo1 {
public static void main(String [] args){

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

}

Output :

no Output

Explanation:  

In this example , it is also valid to have a abstract method in Child class.   

In short , we can make abstract ,Parent class non- abstract method,  in Child Class . Benefit of this concept is we can stop the availability of Parent Class method in Child Class.  

No comments:

Post a Comment