JAVA concepts: abstraction, encapsulation and package
Object-oriented programming languages, such as JAVA, use some modelling concepts that are intuitive and easy to understand. Today we would like to present you three of them: abstraction, encapsulation and package.
First concept – abstraction – gives us the possibility of hiding implementation details of a method or a class. It is useful, when we know that our class will need to contain a method, but we want let the subclasses to decide about its exact implementation.
Second concept is the encapsulation. It consists of hiding fields inside a class by using access modifiers. Instead of acceding directly to the fields, other classes use special public methods. We use encapsulation when we want to protect elements of our classes.
The last concept is the easiest one. A package is similar to a folder in your computer. It regroups related classes and interfaces. It is useful, because it provides a way to organize our project (for instance we can have a package regrouping the interface elements of an application and another with classes describing its behaviour).
The animal example below applies the described concepts.
Animal.java
package animals; public abstract class Animal { public boolean isHungry(){ return true; } //abstract method - each animal will make noise in a different way public abstract void makeNoise(); }
Cat.java
//the class is in the animals package package animals; public class Cat extends Animal{ //variable member or an attribute private String catColour; //instead of using the default constructor we //define a constructor taking one parameters: the _catColour Cat(String _catColour){ catColour = _catColour; } //a function member - implementing the cat behavior public void purr(){ System.out.println("PURRRR!"); } @Override public void makeNoise() { //implementation of the abstract method from the Animal class System.out.println("MEOW!"); } //method used to retrieve the catColour value, but protecting the catColour from modification public String catColour(){ return catColour; } }
Main.java
package animals; public class Main { public static void main(String[] args) { //Animal simpleAnimal = new Animal(); - we CAN'T do this, because Animal class is abstract Cat kitty = new Cat("black"); } }
Leave a Reply
Want to join the discussion?Feel free to contribute!