Can you achieve Runtime Polymorphism by data members

Can you achieve Runtime Polymorphism by data members

Answer: Yes. When you declare data member on parent class then you don’t need to redefine it on child class data member’s value will get resolved to overridden value in actual object type just use or change its value based on your requirement as shown below:

package com.javahonk.polymorphism;

public class FirstStep {
	int x = 1;

	public int getX() {
		return x;
	}
}
package com.javahonk.polymorphism;

public class SecondStep extends FirstStep{

	SecondStep() {
		x = 2;
	}
}
package com.javahonk.polymorphism;

public class ThirdStep extends SecondStep{

	ThirdStep () {  
	    x = 3;  
	  }  
}

 

package com.javahonk.polymorphism;

public class DataMemberPolymorphismTest {

	public static void main(String[] args) {

		FirstStep[] firstSteps = { new FirstStep(), 
				new SecondStep(),
				new ThirdStep() };

		System.out.println("Data Member Polymorphism results: ");
		for (int i = 0; i < firstSteps.length; i++)
			System.out.println(firstSteps[i].getX());

	}

}

 

Output: 

Can you achieve Runtime Polymorphism by data members

 

One thought on “Can you achieve Runtime Polymorphism by data members”
  1. The Original Parent Member value is not changed, still the same after the child.
    Data Member Polymorphism results:
    1
    2
    3
    get now x from FirstStep: 1

    for (int i = 0; i < stepsInSequence.length; i++)
    {
    System.out.println(stepsInSequence[i].getX());
    }
    System.out.println("get now x from FirstStep: " + stepsInSequence[0].x);

Leave a Reply

Your email address will not be published. Required fields are marked *