Encapsulation is restricting
outside access to your object's fields (and even some methods) directly via other methods. Here's a simple example:
say you wanted a class that represented fractions. You would have 2 variables, one for the numerator and one for the denominator. It would be silly to allow someone to set the denominator to zero since that wouldn't be a good fraction. The only way to do this is via encapsulation. If you define the denominator field public, outside sources can access/modify it however they want. If you set it private/protected, outside sources can't access/modify it at all. However, internal sources still have access (and in the case of protected, so do inheriting classes).
So let's create our encapsulated fraction:
public class Fraction
{
private int n, d;
public Fraction(int numerator, int denominator)
{
// numerator can be anything
this.n = numerator;
// don't allow denominator to be 0
this.setDenominator(denominator);
}
public void setDenominator(int denominator)
{
if (denominator != 0)
this.d = denominator;
else
throw new RuntimeException();
}
public int getDenominator()
{
return d;
}
public void setNumerator(int numerator)
{
this.n = numerator;
}
public int getNumerator()
{
return n;
}
public double computeDecimal()
{
return (double)n/d;
}
}
Yes, the point of OOP is to spread out the task, but at a certain point your methods should do something (sometimes a lot of things).
It isn't necessary for you to create your own method, as in this case where you're trying to encapsulate the Random class in it's entirety. Kind of unnecessary, since someone has already encapsulated Random in it's entirety (it's called the Random class). It may be useful to encapsulate if you wanted to restrict access to certain parts of the Random class, but that is not the case here.
Also, encapsulation is generally only used when you have multiple classes. It's impossible to restrict internally access to any of the fields. It's also impossible to restrict access between objects of the same type (including the static instance). So, this is perfectly legal:
public class Cheater
{
private int myNum;
public Cheater(int i)
{
myNum = i;
}
public static int cheat(Cheater other)
{
return other.myNum;
}
}
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
System.out.println("A: Let's play a guessing game!");
Cheater a;
a = new Cheater((int)Math.Random()*100);
System.out.println("B: I'm going to tell you A's number. It's: " + Cheater.cheat(a));
System.out.println("A: Guess a number 0-100: ");
if (new Scanner(System.in).nextInt() == Cheater.cheat(a))
{
System.out.println("A: How'd you know?");
}
else
{
System.out.println("A: Ha, you're wrong");
}
}
}