1// abstraction in java with example
2// abstract class
3abstract class Addition
4{
5 // abstract methods
6 public abstract int addTwoNumbers(int number1, int number2);
7 public abstract int addFourNumbers(int number1, int number2, int number3, int number4);
8 // non-abstract method
9 public void printValues()
10 {
11 System.out.println("abstract class printValues() method");
12 }
13}
14class AbstractMethodExample extends Addition
15{
16 public int addTwoNumbers(int number1, int number2)
17 {
18 return number1 + number2;
19 }
20 public int addFourNumbers(int number1, int number2, int number3, int number4)
21 {
22 return number1 + number2 + number3 + number4;
23 }
24 public static void main(String[] args)
25 {
26 Addition add = new AbstractMethodExample();
27 System.out.println(add.addTwoNumbers(6, 6));
28 System.out.println(add.addFourNumbers(8, 8, 3, 2));
29 add.printValues();
30 }
31}
1// example on abstract class in java
2import java.util.*;
3// abstract class
4abstract class Shape
5{
6 // abstract method
7 abstract void sides();
8}
9class Triangle extends Shape
10{
11 void sides()
12 {
13 System.out.println("Triangle shape has three sides.");
14 }
15}
16class Pentagon extends Shape
17{
18 void sides()
19 {
20 System.out.println("Pentagon shape has five sides.");
21 }
22 public static void main(String[] args)
23 {
24 Triangle obj1 = new Triangle();
25 obj1.sides();
26 Pentagon obj2 = new Pentagon();
27 obj2.sides();
28 }
29}
1 // Method abstraction is the practice of reducing inter-dependency between methods.
2 // The following is an unreasonably simple example, but the point stands:
3 // don't make the person on the other side of your function do more work
4 // than they need to. Include all necessary data transformations in your
5 // methods as is. For instance, take method GetAreaOfCircle:
6
7 // Good practice:
8float GetAreaOfCircle(float radius) {
9 return 3.14f * radius * radius;
10}
11int main() {
12 printf("%d", GetAreaOfCircle(3.0f));
13 getch();
14 return 0;
15}
16
17 // Bad practice:
18float GetAreaOfCircle(float radius) {
19 return radius * radius;
20}
21int main() {
22 float area = 3.14f * GetAreaOfCircle(3.0f);
23 printf("%d", );
24 getch();
25 return 0;
26}