MethodOverrideRule

package com.override;

public class MethodOverrideRule {

	public static void main(String args[])
	{
		// Here reference type and Object type is same
		MethodOverrideRule scls = new MethodOverrideRule();
		OverrideSubclass subcls = new OverrideSubclass();

		// Here reference type is of Super class and Object is of child class
		MethodOverrideRule subOcls = new OverrideSubclass();

		// This will invoke method from Super class
		scls.method();
		// This will onvoke method form sub class
		subcls.method();

		/*
		 * Here overriding will work. Even reference type is of Super class still object type if of Subclass.
		 * Hence Subclass version of method will get invoked.
		 */
		subOcls.method();

		/*
		 * Which overridden method is to be executed depends on the actual Object type at run time.
		 */
	}

	void method(){
		System.out.println("Overriding method without argument in Super");
	}

	int method(String str)
	{
		System.out.println("Overriding method with int argument in Super");
		return 9;
	}
}

class OverrideSubclass extends MethodOverrideRule{

	/*
	 * Here we are overriding the method from super class.
	 * @Override annotation is used to confirm the same. It makes sure the all override rules get followed 
	 * 
	 */
	@Override
	void method(){
		System.out.println("Overriding method without argument in subclass");
	}

	@Override
	int method(String str)
	{
		System.out.println("Overriding method with int argument in subclass");
		return 10;
	}
}

 

Leave A Comment

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