Reputation: 1792
I am new in encapsulation.
I coded a simple java program that can identify if it is given an odd or even number and I tried to use encapsulation with it. I know that encapsulation uses get and set method, but I made it this way.
Is it still considered as encapsulation?
Main
import java.util.Scanner;
public class Implement
{
public static void main(String[]args)
{
Scanner inp = new Scanner(System.in);
System.out.println("Please enter number: ");
int ent = inp.nextInt();
Practice pract = new Practice();
pract.oddeven(ent);
}
}
Practice class
public class Practice
{
public void oddeven(int a)
{
do
{
if(a>=2)
{
a-=2;
}
}
while(a>1);
if(a==1)
{
System.out.println("This number is Odd.");
}
else if(a==0)
{
System.out.println("This number is Even.");
}
}
}
Upvotes: 0
Views: 257
Reputation: 719386
Is it still considered as encapsulation?
Your class has no internal state, so there is no internal state to hide. This means that "encapsulation" (which is all about hiding internal state) is entirely moot.
I should also point out that:
Your oddeven
method is buggy. It won't print anything for numbers less then zero.
That is a horribly inefficient approach to testing for odd or even.
A method that performs a calculation and prints a result to standard output is less useful, flexible and reusable than a method that does the same calculation and returns it.
There are a number of Java style violations in your code:
oddeven
should be oddEven
because "oddeven" isn't an English word.Upvotes: 2
Reputation: 584
For it to be Encapsulated in the method you have to hide whats happening. Thats the true essence of Encapsulation concept. This is done by using two methods:
Getter : gets the value for the main class
Setter : set the value inside the Encapsulation class (Here private variables are used). The following code will show a modification of yours using encapsulation:
public class implement
{
public static void main(String[]args)
{
Practice pract = new Practice();
Scanner inp = new Scanner(System.in);
System.out.println("Please enter number: ");
int ent = inp.nextInt();
pract.setNum(ent);
if(pract.getNum() == 1){
System.out.println("This number is Odd");
}else if (pract.getNum() == 0){
System.out.println("This is Even");
}
}
}
practise class:
public class Practice
{
private int x;
public int getNum(){
return x;
}
public void setNum(int a){
x = a;
do{if(x >= 2)
x -=2;
}while(x>1);
}
}
Upvotes: 0
Reputation: 37083
Encapsulation applies at object level and is specific to Method's and fields. You just have a method which acts upon an input parameter and has nothing to do with encapsulation.
Oracle's definition to data encapsulation is : "Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming."
Upvotes: 0