Talking about code, an abstraction is simply a piece of code that describes a real world "thing". Most times you can't describe the whole "thing", but you can describe it's main characteristics, which, in your code, would be called attributes.
One example of an abstraction would be a Restaurant: You go, you ask for the menu and select whatever you want to eat... but you don't eat the paper: You select what you want looking at an abstraction of it (the menu)... that abstraction may just say "Eggs & Bacon", but when the waiter brings your order it has a pair of eggs (scrambled), two pieces of crispy bacon and some other things... The menu is just a simple abstraction of the real thing.
Take the Bicycle example in the Java Tutorials: The bicycle has attributes:
- Speed
- Gear
- Cadence
You're not interested (in this example) in any other characteristics of the bicycle... so this is an abstraction.
Now, about encapsulation: when writing code, you want your object's attributes to be modified only in a "propper" way: If you change the speed (again the Bicycle example) you may have to also change the cadence and/or change the gear. So you declare the attributes private
and update them only through public
methods, and, in these methods, you ensure that all the attributes have coherent values:
public class Bicycle {
private int speed, gear, cadence;
/**
* Default constructor
*/
public Bicycle() {
speed = 0;
gear = 1;
cadence = 0;
}
/**
* An example
*/
public void setSpeed(int speed) {
this.speed = speed;
/*
You can set the value of the other attributes here if you want to
*/
}
/**
* Another example
*/
public void gearUp() {
if(gear < 5)
gear++;
/*
Here you are preventing other methods to set the gear to
a value higher than 5.
*/
}
/**
* Another one
*/
public void gearDown() {
if(gear > 1)
gear--;
/*
Here you are preventing other methods to set the gear to
a value lower than 1.
*/
}
}