method abstraction code example

Example 1: Abstraction in java

// abstraction in java with example
// abstract class
abstract class Addition
{
   // abstract methods
   public abstract int addTwoNumbers(int number1, int number2);
   public abstract int addFourNumbers(int number1, int number2, int number3, int number4);
   // non-abstract method
   public void printValues()
   {
      System.out.println("abstract class printValues() method");
   }
}
class AbstractMethodExample extends Addition
{
   public int addTwoNumbers(int number1, int number2)
   {
      return number1 + number2;
   }
   public int addFourNumbers(int number1, int number2, int number3, int number4)
   {
      return number1 + number2 + number3 + number4;
   }
   public static void main(String[] args)
   {
      Addition add = new AbstractMethodExample();
      System.out.println(add.addTwoNumbers(6, 6));
      System.out.println(add.addFourNumbers(8, 8, 3, 2));
      add.printValues();
   }
}

Example 2: Abstraction in java

// example on abstract class in java
import java.util.*;
// abstract class
abstract class Shape
{
   // abstract method
   abstract void sides();
}
class Triangle extends Shape
{
   void sides()
   {
      System.out.println("Triangle shape has three sides.");
   }
}
class Pentagon extends Shape
{
   void sides()
   {
      System.out.println("Pentagon shape has five sides.");
   }
   public static void main(String[] args)
   {
      Triangle obj1 = new Triangle();
      obj1.sides();
      Pentagon obj2 = new Pentagon();
      obj2.sides();
   }
}

Example 3: method abstraction

// Method abstraction is the practice of reducing inter-dependency between methods.  
 // The following is an unreasonably simple example, but the point stands: 
 // don't make the person on the other side of your function do more work 
 // than they need to.  Include all necessary data transformations in your 
 // methods as is.  For instance, take method GetAreaOfCircle: 

 // Good practice: 
float GetAreaOfCircle(float radius) {
	return 3.14f * radius * radius;
}
int main() {
	printf("%d", GetAreaOfCircle(3.0f));
    getch();
    return 0;
}

 // Bad practice: 
float GetAreaOfCircle(float radius) {
	return radius * radius;
}
int main() {
	float area = 3.14f * GetAreaOfCircle(3.0f);
	printf("%d", );
    getch();
    return 0;
}

Tags:

Java Example