Skip to content

Abstract method example C Sharp program

Abstract method example C# program –

  • Abstract methods don’t have body, they just have method signature.
  • If a class has an abstract method it should be declared abstract, the vice versa is not true, which means an abstract class doesn’t need to have an abstract method compulsory.
  • If a regular class extends an abstract class, then the class must have to implement all the abstract
/*
   * Abstract method example java program 
 */
abstract class CompositeMath {
 
	/*
	 * These are i.e.AreaofCircle(int r) and AreaofRectangle(int l,int w) are
	 * two abstract methods which need to be implemented in the child/derived
	 * class
	 */
	public abstract int AreaofCircle(int r);
 
	public abstract int AreaofRectangle(int l, int w);
 
	public void Display() {
		Console.WriteLine("The return results are:");
	}
}
 
class Mensuration : CompositeMath {
 
	/*
	 * In case if we don't provide implementation to these methods then program
	 * will throw compilation error
	 */
 
	// implementation of first abstract method
	public override int AreaofCircle(int r) {
 
		return (int) (3.14 * r * r);
	}
 
	// implementation of 2nd abstract method
	public override int AreaofRectangle(int l, int w) {
 
		return l * w;
	}
}
 
// client class
public class Maths {
 
	public static void Main(String[] args) {
 
		// passing the reference of the base class
		// in order to call implemented methods
		CompositeMath cm = new Mensuration();
		cm.Display();
		Console.WriteLine(cm.AreaofCircle(5));
		Console.WriteLine(cm.AreaofRectangle(5, 6));
 
	}
 
}

Output:

The return results are:
78
30


Published inC# Programming Examples