OOP: 1 Understand the Difference Between Procedural and Object-Oriented Programming
One of the four basic principles of object-oriented programming (OOP) is encapsulation. Encapsulation is a mechanism of hiding data implementation by restricting access to public methods.
This topic was my first task in the OOP lesson. For example, this is the procedural version that I wrote in C.
#include <stdio.h>
#define PI 3.14159265359
int main(){
double r;
scanf("%lf\n", &r);
/*For example, I can add to the main
r = 3.0;
to directly reference variable r. *\
printf("Radius: %.2f\n", r);
printf("Circumference: %.2f\n", 2 * PI * r);
printf("Area: %.2f\n", PI * r * r);
return 0;
}
The solution is to encapsulate the method using Java class and access modifier.
For example, this is the circle class.
package id.ac.its.fortunela.ling;
public class Lingkaran {
private double radius;
private double pi = 3.14159265359;
public void setRadius(int radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public double getKeliling() {
return 2 * pi * getRadius();
}
public double getLuas() {
return pi * pow(getRadius(),2);
}
}
And this is the main class.
package id.ac.its.fortunela.ling;
import java.util.Scanner;
import java.text.DecimalFormat;
public class MainApp {
public static void main(String[] args) {
/*As you can see, it is not possible to directly reference variable radius. *\
Lingkaran li = new Lingkaran();
Scanner in = new Scanner(System.in);
double d = in.nextDouble();
/*Using setRadius makes variable radius can't directly referenced*\
li.setRadius(d);
in.close();
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println("Radius: " + numberFormat.format(li.getRadius()));
System.out.println("Luas: " + numberFormat.format(li.getLuas()));
System.out.println("Keliling: " + numberFormat.format(li.getKeliling()));
}
}
Well, my Java code wasn't looking good when I checked it now. So above is the corrected version. You know, I was confident in OOP before, but now I am anxious that my grades might be... Well, I hope my GPA is more than 3.5 at the least, so I can take some extra credit this term.
Komentar
Posting Komentar